定義協(xié)程必須指定其CoroutineScope,它會(huì)跟蹤所有協(xié)程,同樣它還可以跟蹤取消它所啟動(dòng)的協(xié)程.
協(xié)程作用域:
GlobalScope. 生命周期是process 級(jí)別的,即時(shí)Activity 或 fragment已經(jīng)銷毀,協(xié)程仍然在執(zhí)行.
MainScope. 在Activity 中使用,可以在onDestroy()中取消.
viewModelScope. 只能在ViewModel 中使用,綁定ViewModel 的生命周期.
lifecycleScope. 只能在Activity,fragment 中使用,會(huì)綁定Activity 和 Fragment生命周期.
coroutineScope 與runBlocking 協(xié)程作用域
- runBlocking是常規(guī)函數(shù),而coroutineScope 是掛起函數(shù).
- 它們都會(huì)等待其協(xié)程以及所有子協(xié)程結(jié)束, 主要區(qū)別在于runBlocking 方法會(huì)阻塞當(dāng)前線程來(lái)等待,而coroutineScope只是掛起,會(huì)釋放底層線程用于其他用途.
coroutineScope 與 supervisorScope 協(xié)程作用域
- coroutineScope: 一個(gè)協(xié)程失敗了,所有其他兄弟協(xié)程也會(huì)被取消
- supervisorScope: 一個(gè)協(xié)程失敗了,不會(huì)影響其他兄弟協(xié)程
runBlocking {
coroutineScope {
val job1 = launch {
delay(400)
println("job1 fininsh")
}
val job2 = launch {
delay(200)
println("job2 fininsh") // ① 程序打印 job2 fininsh
throw IllegalArgumentException() // ② 程序崩潰 協(xié)程體取消
}
}
}
runBlocking {
coroutineScope {
val job1 = launch {
delay(400)
println("job1 fininsh") // ② 程序打印 job1 fininsh
}
val job2 = async {
delay(200)
println("job2 fininsh") // ① 程序打印 job2 fininsh
"HHH"
throw IllegalArgumentException()
}
}
}