I have code that is essentially the following:
var job: Job? = null
fun startJob() = runBlocking(dispatcher) {
job = CoroutineScope(dispatcher).launch { myJob() }
}
suspend fun myJob() {
// work block 1
...
yield()
// work block 2
...
yield()
// work block 3
...
yield()
...
}
fun cancelJob() = runBlocking(dispatcher) {
job?.cancelAndJoin()
}
fun main() {
startJob()
cancelJob()
}
When I run the above with dispatcher = Dispatchers.IO or Dispatchers.Default, it works fine. However, setting dispatcher = TestCoroutineDispatchers simply hangs at the cancelAndJoin().
I'm suspecting it's related to TestCoroutineDispatcher's behavior in handling yield(). According to this, yield() will only resume if runCurrent() is called. But given the structure of my code, I'm not sure where to call runCurrent(), or if it's even the right approach.