https://kotlinlang.org logo
Title
p

Patrick Steiger

04/07/2023, 10:51 PM
Can’t
runCurrent
be used to advance the event loop in case of nested coroutines launched with
UnconfinedTestDispatcher
? Below code outputs
1 2 4 3 5
fun test() = runTest(UnconfinedTestDispatcher()) {
  println(1)
  launch {
    println(2)
    launch { println(3) }
    runCurrent()
    println(4)
  }
  println(5)
}
k

Ky

04/10/2023, 11:41 PM
I thought we have no control over execution order with 'Unconfined'. Everything is executed eagerly?
p

Patrick Steiger

04/10/2023, 11:43 PM
Except when there are nested coroutines, in order to prevent
StackOverflowException
Same for
Dispatchers.Main.immediate
In which case it forms an event loop
Seems we can’t control this event loop at all in tests.
k

Ky

04/11/2023, 12:16 AM
So you would see your expected behavior if you ran this same code in application code inside 'Dispatchers.UNCONFINED'? although those clock operations are only available in coroutines test package
p

Patrick Steiger

04/11/2023, 12:17 AM
Same code would output the same outside tests, yes
k

Ky

04/11/2023, 12:21 AM
So it seems there is no case where we control execution order when using an unconfined dispatcher in kotlin. If the behavior is no different between tests and app code
p

Patrick Steiger

04/11/2023, 12:25 AM
It’s been some time and I don’t remember exactly in which context I wanted to manually advance the event loop in tests, but I think In the end I chose to run runTest in standard dispatcher and using CoroutineStart.UNDISPATCHED in real code Real code does want to avoid dispatch
Ok based on this I guess it’s considered a bug