简体   繁体   English

Kotlin:在创建协程范围时是否应将作业与调度程序一起传递

[英]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 default Job() is created.如果给定的上下文不包含Job元素,则创建一个默认的Job() This way, cancellation or failure or any child coroutine in this scope cancels all the other children, just like inside coroutineScope 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 and Dispatchers.Main context elements.结果范围具有SupervisorJobDispatchers.Main上下文元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM