如何在不使用 GlobalScope 的情况下在主线程上启动协程?

How to start a coroutine on main thread without using GlobalScope?

每当我想在主线程上启动协程时,

fun main(args: Array<String>) {
    GlobalScope.launch {
        suspededFunction()
    }
}

suspend fun suspededFunction() {
    delay(5000L) //heavy operation
}

GlobalScope 被高亮显示,总是嘲讽它的用法很微妙,需要小心。

GlobalScope 涉及哪些细节,重要的是我如何在不使用 GlobalScope 的情况下启动协程?

要在不使用 GlobalScope 的情况下启动协程,可以这样做:

val job = Job()
val scope = CoroutineScope(job)

scope.launch {
        suspededFunction()
    }

如评论中所述,一些 classes 已经有可用的范围,例如 ViewModel class 和 viewModelScope

在Activity或Fragment中你可以如下:

//not recommended to use co-routines inside fragment or activity class
// this is just for example sack shown here.
// otherwise you have to do all your processing inside viewmodel
    class Fragment : CoroutineScope by MainScope() {
             
            
        ... 
             override fun onDestroy() {
                super.onDestroy()
                cancel()
             }
        
        }

Kotlin 已经创建了一些作用域。你可以根据你的情况使用它。您还可以创建自己的范围。但我建议一开始最好使用已经创建的 查看官方文档https://developer.android.com/topic/libraries/architecture/coroutines

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewBinding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(viewBinding.root)

    lifecycleScope.launch {
        //for activity
    }


}



  //for viewmodel
suspend fun abc() = viewModelScope.launch { 
     
    }