简体   繁体   中英

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. While creating the uiScope should i be passing a job() as well?

The documentation of fun CoroutineScope is clear on this:

If the given context does not contain a Job element, then a default Job() is created. This way, cancellation or failure or any child coroutine in this scope cancels all the other children, just like inside coroutineScope block.

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. It takes no arguments and constructs exactly the scope you need. From the docs:

The resulting scope has SupervisorJob and Dispatchers.Main context elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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