It seems that adding `yield()`s in between and a `...
# coroutines
d
It seems that adding `yield()`s in between and a
delay(1000L)
helps... not sure what the problems was though... 🤔.
s
It is probably that they collect in same scope.
d
But it launches a coroutine for each (
launchIn(scope)
)
s
Or your test finishes before all onEach gets called
Let me try on ide
d
That's covered by the delay, but doesn't explain the yeild
yield
s
it is not about delay. yield is enough. And probably reason is runBlocking’s scope finishes before first onEach find time to execute
Copy code
runBlocking {
  println("start")

  val job1 = state
      .onEach { println("$it-1") }
      .launchIn(scope)
  println("here")

  state.value = 2
  val job2 = state
      .onEach { println("$it-2") }
      .launchIn(scope)

  state.value = 3
  println("finished")

  job1.cancelAndJoin()
  job2.cancelAndJoin()
}
You need to cancel your jobs of launchIns. otherwise runBlockings scope finishes and script finish without checking val scopes state.
you can also just cancel the val scope at the end of runBlocking
Copy code
scope.cancel()
d
Thanks! With
scope.cancel()
I got completely different results..
s
It is a race condition and leak of scope. scope continue running when runblocking finishes but when runblocking finishes all script finishes 😅
d
Thanks for the explanation 😊!