我在做
private val uiScope = CoroutineScope(Dispatchers.Main)
创建一个协程镜,并使用它在我的片段中启动协程。
uiScope.launch {
withContext(Dispatchers.Default) {
....
}
....
}
当片段从窗口分离时,我对uiScope进行了取消。在创建uiScope时,我还应该传递一个job()吗?
最佳答案
fun CoroutineScope
的文档对此很明确:
If the given context does not contain a
Job
element, then a defaultJob()
is created. This way, cancellation or failure or any child coroutine in this scope cancels all the other children, just like insidecoroutineScope
block.
对于顶级范围而言,使用传播其子项故障的作业不是最佳选择。您应该改为使用
MainScope
工厂功能。它不带任何参数,并精确地构造您需要的范围。从文档:The resulting scope has
SupervisorJob
andDispatchers.Main
context elements.
关于kotlin - Kotlin:在创建协程范围时,是否应将工作与调度程序一起传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57165228/