https://kotlinlang.org logo
Title
d

dave08

05/10/2020, 7:20 AM
It seems that adding `yield()`s in between and a
delay(1000L)
helps... not sure what the problems was though... 🤔.
s

Sinan Kozak

05/10/2020, 8:28 AM
It is probably that they collect in same scope.
d

dave08

05/10/2020, 8:29 AM
But it launches a coroutine for each (
launchIn(scope)
)
s

Sinan Kozak

05/10/2020, 8:36 AM
Or your test finishes before all onEach gets called
Let me try on ide
d

dave08

05/10/2020, 8:37 AM
That's covered by the delay, but doesn't explain the yeild
yield
s

Sinan Kozak

05/10/2020, 9:08 AM
it is not about delay. yield is enough. And probably reason is runBlocking’s scope finishes before first onEach find time to execute
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
scope.cancel()
d

dave08

05/10/2020, 9:39 AM
Thanks! With
scope.cancel()
I got completely different results..
s

Sinan Kozak

05/10/2020, 9:40 AM
It is a race condition and leak of scope. scope continue running when runblocking finishes but when runblocking finishes all script finishes 😅
d

dave08

05/10/2020, 10:51 AM
Thanks for the explanation 😊!