Doru N.
12/23/2021, 9:01 PMflow {
// The WRONG way to change context for CPU-consuming code in flow builder
withContext(Dispatchers.Default) {
for (i in 1..3) {
Thread.sleep(100) // pretend we are computing it in CPU-consuming way
emit(i) // emit next value
}
}
}
.onEach { value -> println(value) }
.launchIn(scope)
crashes with java.lang.IllegalStateException: Flow invariant is violated…,
but this one does not:
flowOf(1, 2, 3)
.transformLatest {
withContext(Dispatchers.Default) {
Thread.sleep(100) // pretend we are computing it in CPU-consuming way
println("emitting $it, on thread: ${Thread.currentThread().name}")
emit(it) // emit next value
}
}
.onEach {
println("collect.onEach: $it, on thread: ${Thread.currentThread().name}")
}
.launchIn(scope)
to me, it should be the same case as the first (should crash with same exception). What am I missing here?
logs for 2nd sample is this:
emitting 1, on thread: DefaultDispatcher-worker-1
collect.onEach: 1, on thread: main
emitting 3, on thread: DefaultDispatcher-worker-1
collect.onEach: 3, on thread: main
bezrukov
12/23/2021, 9:09 PMchannelFlow { }
builder instead of flow {}
and it won't crashDoru N.
12/23/2021, 9:13 PMbezrukov
12/23/2021, 9:13 PM