what's easiest way to "force" a suspension point w...
# coroutines
r
what's easiest way to "force" a suspension point without using delay function? I would like to force a suspension point but also not delay by any amount of time.
o
yield()
r
Ah. Yes should work indeed! I just checked docs and it doesn't run if your dispatcher is unconfined and my case it is. Maybe I have to rethink what I'm doing. Thanks though! i didn't even think about yield haha
d
Are you using this forced suspension to "lift" a coroutine from the current thread. By "lift" I mean to stop it from running immediately in the current coroutine.
r
@Dominaezzz I just need something that forces the current coroutine to suspend. If I have to switch to another thread to do so, then so be it.
But if I could somehow force a suspend (with Dispatchers.Unconfined) on the same thread that'd be great.
Copy code
private suspend fun testSuspendFunction() =
    withContext(Executors.newSingleThreadExecutor().asCoroutineDispatcher()) {
        Unit
    }
I'll probably end up going with this for my use case^
j
FYI yield will not force suspension on some dispatchers
r
Copy code
* If the coroutine dispatcher is [Unconfined][Dispatchers.Unconfined], this
* functions suspends only when there are other unconfined coroutines working and forming an event-loop.
* For other dispatchers, this function calls [CoroutineDispatcher.dispatch] and
* always suspends to be resumed later regardless of the result of [CoroutineDispatcher.isDispatchNeeded].
* If there is no [CoroutineDispatcher] in the context, it does not suspend.
j
r
@jw Thanks a lot! I actually need something almost exactly like that. I'd like to force suspend and then throw. My purposes are for unit testing some lower level coroutine code I wrote