I’m starting a coroutine with `start=CoroutineStar...
# coroutines
p
I’m starting a coroutine with
start=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
Copy code
private suspend fun dispatchIfNeeded() {
  suspendCoroutineUninterceptedOrReturn { c ->
    suspend {}.startCoroutine(c)
    COROUTINE_SUSPENDED
  }
  coroutineContext.ensureActive()
}
To future readers whom it might interest, I settled with
Copy code
private 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
}