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 defaultJob()
is created. This way, cancellation or failure or any child coroutine in this scope cancels all the other children, just like insidecoroutineScope
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
andDispatchers.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.