Kotlin 协程如何获取当前线程的 CoroutineScope?

Sud*_*lan 8 kotlin kotlin-coroutines

在 Kotlin 协程中,想要为当前线程创建一个引用并在以后使用它。

fun myFuncion(){
    //save current Thread CoroutineScope
    var currentCoroutineScope : CoroutineScope // <How to create?>
    GlobalScope.launch { 
        //Do something 001
        currentCoroutineScope .launch {
            //Do something 002

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙解决这个问题吗?

Max*_*Max 2

您可以使用保存对协程范围的引用

val scope = CoroutineScope(Dispatchers.Default)
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它

fun myFuncion() {
    scope.launch {
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)

评论更新:

如果你从主线程调用你的myFunction()那么你可以做这样的事情

fun myFuncion() {
        scope.launch {
            // do something
            withContext(Dispatchers.Main) { 
                //Do something 002
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)