https://kotlinlang.org logo
Title
r

Robert Williams

08/08/2022, 4:27 PM
I’ve just discovered that
CoroutineDispatcher.dispatch
method can be called directly in application code and this seems… problematic
For example I can easily write code that breaks structured concurrency as long as I have a Dispatcher:
dispatcher.dispatch(dispatcher) {
//some blocking code
}
and I can’t find much in the documentation or other sources that suggests we shouldn’t do this
So questions are: • Are there actually legitimate uses in application code (I guess it’s used internally but doesn’t seem like it should be public)? • Can it be hidden in public API? If not does it deserve a scary warning? • Is it actually better/ worse than using GlobalScope to do the same thing? That has lots of very scary warnings.
e

ephemient

08/08/2022, 4:52 PM
it has to be public to allow for custom and delegating dispatchers
it's not any more dangerous than
dispatcher.asExecutor().execute {
  //some blocking code
}
z

Zach Klippenstein (he/him) [MOD]

08/08/2022, 4:54 PM
It's very easy to write all kinds of code that doesn't use structured concurrency even without dropping to low-level apis like this.
r

Robert Williams

08/08/2022, 5:20 PM
You correctly mention it’s a low-level API so maybe the real problem is that it’s very common and recommended practice to pass into classes that need to do async work
I wonder if we lose anything else by using CoroutineContext instead when passing CoroutineDispatcher 🤔
Obviously wouldn’t stop you using eg Dispatcher.IO directly but it makes it harder to do wrong things and hides the low-level APIs which mostly aren’t needed
z

Zach Klippenstein (he/him) [MOD]

08/08/2022, 5:26 PM
It's generally better to accept a context vs a specific type of context element, since it is much more flexible
r

Robert Williams

08/08/2022, 5:32 PM
Yeah, I’ll try to do this going forward but doesn’t help that Google’s best practices use CoroutineDispatcher directly everywhere https://developer.android.com/kotlin/coroutines/coroutines-best-practices#inject-dispatchers
e

ephemient

08/08/2022, 5:35 PM
for dispatchers I don't think that's a good pattern anyway, since there's multiple you might want to inject (Default, IO) with the same type
if you use dagger, you'd need qualifiers to disambiguate them (which is doable, but annoying)
a

Adam Powell

08/08/2022, 7:18 PM
Fwiw we've been moving further away from that and back to
CoroutineContext
in more APIs