https://kotlinlang.org logo
#coroutines
Title
# coroutines
r

Rechee Jozil

06/11/2020, 6:17 PM
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

octylFractal

06/11/2020, 6:19 PM
yield()
r

Rechee Jozil

06/11/2020, 6:23 PM
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

Dominaezzz

06/11/2020, 6:29 PM
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

Rechee Jozil

06/11/2020, 6:32 PM
@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

jw

06/11/2020, 6:41 PM
FYI yield will not force suspension on some dispatchers
r

Rechee Jozil

06/11/2020, 6:42 PM
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

jw

06/11/2020, 6:42 PM
r

Rechee Jozil

06/11/2020, 6:44 PM
@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
6 Views