Patrick Steiger
04/05/2023, 1:07 AMstart=CoroutineStart.UNDISPATCHED
but at some point I want to check the dispatcher in context and dispatch if needed. yield
would do but it does not respect immediate dispatchers, which I want to. I came up with the following, but not sure if it’s safe or if there’s a better approach, suggestions welcome
private suspend fun dispatchIfNeeded() {
suspendCoroutineUninterceptedOrReturn { c ->
suspend {}.startCoroutine(c)
COROUTINE_SUSPENDED
}
coroutineContext.ensureActive()
}
Patrick Steiger
04/09/2023, 3:54 AMprivate suspend inline fun dispatchIfNeeded() {
suspendCoroutineUninterceptedOrReturn sc@ { cont ->
val context = cont.context
val dispatcher = context[ContinuationInterceptor] as CoroutineDispatcher
if (!dispatcher.isDispatchNeeded(context)) return@sc Unit
context.ensureActive() // check for cancellation before dispatching
cont.intercepted().resume(Unit) // will dispatch
COROUTINE_SUSPENDED
}
coroutineContext.ensureActive() // don't resume normally if coroutine was cancelled after
}