[英]Kotlin: Should a job be passed along with a dispatcher while creating a coroutine scope
I am doing我在做
private val uiScope = CoroutineScope(Dispatchers.Main)
to create a coroutinescope and using that to launch the coroutines in my fragment.创建一个协程范围并使用它来启动我的片段中的协程。
uiScope.launch {
withContext(Dispatchers.Default) {
....
}
....
}
I do a cancel on uiScope when the fragment is detached from window.当片段从窗口分离时,我在 uiScope 上取消。 While creating the uiScope should i be passing a job() as well?
在创建 uiScope 时,我还应该传递一个 job() 吗?
The documentation of fun CoroutineScope
is clear on this: fun CoroutineScope
的文档fun CoroutineScope
很清楚:
If the given context does not contain a
Job
element, then a defaultJob()
is created.如果给定的上下文不包含
Job
元素,则创建一个默认的Job()
。 This way, cancellation or failure or any child coroutine in this scope cancels all the other children, just like insidecoroutineScope
block.这样,取消或失败或此范围内的任何子协程都会取消所有其他子
coroutineScope
,就像在coroutineScope
块中一样。
Using a job that propagates the failure of its children is not the best choice for the top-level scope.使用传播其子项失败的作业不是顶级范围的最佳选择。 You should instead use the
MainScope
factory function.您应该改用
MainScope
工厂函数。 It takes no arguments and constructs exactly the scope you need.它不接受任何参数并准确构建您需要的范围。 From the docs:
从文档:
The resulting scope has
SupervisorJob
andDispatchers.Main
context elements.结果范围具有
SupervisorJob
和Dispatchers.Main
上下文元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.