Is it possible to set the default dispatcher to Di...
# coroutines
p
Is it possible to set the default dispatcher to Dispatches.Main? I almost never want the default dispatcher and like to run my launch always on the main dispatcher and only switch the context when necessary
d
For GlobalScope?
p
No, the
Dispatchers.default
d
Default dispatcher is defined by the scope you use.
p
I don't think so
Copy code
/**
     * The default [CoroutineDispatcher] that is used by all standard builders like
     * [launch][CoroutineScope.launch], [async][CoroutineScope.async], etc
     * if no dispatcher nor any other [ContinuationInterceptor] is specified in their context.
     *
     * It is backed by a shared pool of threads on JVM. By default, the maximal level of parallelism used
     * by this dispatcher is equal to the number of CPU cores, but is at least two.
     * Level of parallelism X guarantees that no more than X tasks can be executed in this dispatcher in parallel.
     */
    @JvmStatic
    public actual val Default: CoroutineDispatcher = createDefaultDispatcher()
d
val scope = MainScope()
scope.launch [ runsInMainThread() }
Because scope dispatcher is Dispatchers.Main
p
I don't get what you're saying
d
cf:
if no dispatcher nor any other [ContinuationInterceptor] is specified in their context.
If your scope specifies a dispatcher, this is the default one used by
launch
if none specified in parameters
☝️ 1
d
Can you share a code snippet where you are explicitly using Dispatchers.Main
What Geoffrey is saying is exactly right.
p
Still don't get it. I don't have a snippet, I think that the default of
Dispatchers.Default
not being
Dispatchers.Main
is not right
a
you should never run into this being a problem because any
CoroutineScope
you launch into should have a dispatcher configured already. You should be creating scopes through standardized utilities so that you never have to think about it, e.g.
LifecycleOwner.lifecycleScope
,
ViewModel.viewModelScope
, or similar definitions you write yourself
👍 1
If you find yourself regularly creating one-off scopes by hand to launch into, you're probably not getting the full benefits of structured concurrency
Dispatchers.Main
would make a poor default anyway; it would be an unnecessarily UI-centric perspective for a general tool like coroutines to adopt
and even if you did manage to set
Dispatchers.Default
to point at
Dispatchers.Main
for your app, it would probably have catastrophic effects on the behavior of libraries you use that assume
Dispatchers.Default
is a pool of worker threads for CPU-bound work. Those libraries would start blocking your main thread very quickly if you changed that assumption out from under them 🙂
d
And maybe all platform don't have a 'main' dispatcher. kotlinx is multiplatform ready
p
Thanks for the interesting insights, totally makes sense