Dontsu
02/12/2025, 2:34 AMwithContext(Dispatchers.Main)
produce the same effect as specifying Dispatchers.Main
as a parameter to launch
?
I think it may be same effect. but i'm not sure..
private var supervisorJob = SupervisorJob()
private var scope = CoroutineScope(supervisorJob + Dispatchers.Default)
// 1
scope.launch {
withContext(Dispatchers.Main) {
// some code
}
}
// 2
scope.launch(Dispatchers.Main) {
// some code
}
jw
02/12/2025, 2:37 AMDontsu
02/12/2025, 2:52 AMlaunch
, async
etc.., new coroutine is created. but does it need to dispatch the same dispatcher(in this case Dispatchers.Default) even though the initial scope(parent scope) uses Dispatchers.Default? Until now, I always thought that child coroutines would automatically follow the parent's dispatcher, so I didn't know that they would be dispatched again when created.jw
02/12/2025, 2:55 AMRunnable
which is already executing on an Executor
can enqueue additional `Runnable`s on the same executor but those must wait until the current one is finished (or until another thread picks them up).
If you explicitly want a new coroutine to be entered synchronously (i.e., without dispatch) you can pass start = CoroutineStart.UNDISPATCHED
. This can be useful if you want to ensure that the new child coroutine reaches its first suspension point before doing something else.ephemient
02/12/2025, 3:20 AMDispatchers.Main.immediate
will start undispatched if Main
is the current dispatcherjw
02/12/2025, 3:22 AMUnconfined
. I wasn't trying to be exhaustive, but there are indeed only a couple ways it can happen.Dontsu
02/12/2025, 5:09 AMephemient
02/12/2025, 5:11 AMephemient
02/12/2025, 5:13 AMephemient
02/12/2025, 5:15 AMCoroutineStart.LAZY
which doesn't start the coroutine at all and ATOMIC
which forces dispatch, but you should generally not use eitherDontsu
02/12/2025, 5:28 AM