answer is: not exactly. It all works with the assu...
# coroutines
p
answer is: not exactly. It all works with the assumption that the underlying executor will throw if shutdown. I was looking at “bad” code that’s wrapping an android handler and not throwing if the task is rejected, hence blocking forever
l
You can do use
asCoroutineDispatcher()
on a
Handler
instance, it's part of kotlinx-coroutines-android, I think the implementation it provides is correct for this edge case.
z
What’s the fix for
asCoroutineDispatcher
? I didn’t think the
dispatch
method was allowed to throw, so the execution rejected exception approach wouldn’t work?
p
Great question! Executor.asCoroutineDispatcher() catches rejection and delegates the work to Dispatchers.IO : https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/src/Executors.kt#L92-L100
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/java.util.concurrent.-executor/as-coroutine-dispatcher.html
If the underlying executor throws RejectedExecutionException on attempt to submit a continuation task (it happens when closing the resulting dispatcher, on underlying executor shutdown, or when it uses limited queues), then the Job of the affected task is cancelled and the task is submitted to the Dispatchers.IO, so that the affected coroutine can cleanup its resources and promptly complete.
Do you want to send the PR, or should I do it?
@louiscad you’re welcome to. This might be quite involved (look at the Executors impl), maybe worth filing an issue?