Hey, I’m trying the new Kotlin Flows experimental API and write a simple example by following this link.
@ExperimentalCoroutinesApi
val ints: Flow<Int> = flow {
for (i in 0..5) {
delay(100)
println(message = "Emitting data $i -> $coroutineContext")
emit(i)
}
}.catch {
println("Exception caught -> $coroutineContext")
return@catch this.emitAll(flowOf(103, 104, 105))
}
@ExperimentalCoroutinesApi
suspend fun main() {
val time = measureTimeMillis {
ints.buffer().onCompletion {
println("completed with thread $coroutineContext")
}.collect {
delay(100)
println("$coroutineContext -> $it")
}
}
val time2 = measureTimeMillis {
ints.buffer().onCompletion {
println("completed2 with thread $coroutineContext")
}.collect {
delay(100)
println("$coroutineContext 2 -> $it")
}
}
println("Number of thread use -> ${Thread.activeCount()}")
println("Executed time -> ${time + time2} ms")
}
Now if I try to run the above code it uses 13 threads count but if I change the suspend main fun
to fun main = runBlocking
the program uses 2 threads.
I’m using a xeon processor with 6 cores and 32Gb ram.
Can someone please explain to me what’s happening here. Thanks in advance.