ec
05/10/2020, 4:15 PMfun main() = runBlocking {
val fl1 = flow {
for (i in 1..3)
emit(i)
}
val time = measureTimeMillis {
fl1.map { slowComp(it) }.buffer().collect { println(it) }
}
println("TIME: $time")
}
suspend fun slowComp(i: Int): Int {
delay(1000)
return i * i
}octylFractal
05/10/2020, 4:16 PMrunBlocking event loopoctylFractal
05/10/2020, 4:17 PMrunBlocking(Dispatchers.Default) and see if that works outoctylFractal
05/10/2020, 4:17 PMdelayoctylFractal
05/10/2020, 4:17 PMoctylFractal
05/10/2020, 4:18 PMslowComp doesn't make it parallelec
05/10/2020, 4:19 PMec
05/10/2020, 4:19 PMoctylFractal
05/10/2020, 4:19 PMec
05/10/2020, 4:20 PMoctylFractal
05/10/2020, 4:20 PMoctylFractal
05/10/2020, 4:20 PMec
05/10/2020, 4:21 PMec
05/10/2020, 4:21 PMoctylFractal
05/10/2020, 4:21 PMoctylFractal
05/10/2020, 4:21 PMdelay will remove your coroutine from the thread, unlike a spin-wait which will block on the threadoctylFractal
05/10/2020, 4:22 PMdelay will use some sort of timer to determine when to resume your coroutine, e.g. ScheduledExecutorServiceec
05/10/2020, 4:22 PMoctylFractal
05/10/2020, 4:27 PMflow {
coroutineScope {
fl1.collect {
emit(async { slowComp(it) })
}
}
}.buffer().map { it.await() }.collect { println(it) }
this is certainly non-trivial, but https://github.com/Kotlin/kotlinx.coroutines/issues/1147 is still under the design processoctylFractal
05/10/2020, 4:27 PMec
05/10/2020, 4:30 PMthana
05/10/2020, 5:25 PMcollect and emit might runn in parallel due to buffer . but as the only delay is in collect buffer can't help here as the order of execution doesn't change.
if you'd delay(500) in both, the emitting for loop as well as in slowcomp things might change