I’ve just discovered that `CoroutineDispatcher.dis...
# coroutines
r
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:
Copy code
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
it has to be public to allow for custom and delegating dispatchers
it's not any more dangerous than
Copy code
dispatcher.asExecutor().execute {
  //some blocking code
}
z
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
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
It's generally better to accept a context vs a specific type of context element, since it is much more flexible
r
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
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
Fwiw we've been moving further away from that and back to
CoroutineContext
in more APIs