My intuition was it would take less than 3 sec to ...
# coroutines
e
My intuition was it would take less than 3 sec to complete this, since I'm buffering slow comp but it still takes around 3 sec why?
Copy code
fun 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
}
o
you didn't change the dispatcher, so all coroutines still run on the single
runBlocking
event loop
try doing
runBlocking(Dispatchers.Default)
and see if that works out
err, actually, nvm that, you use
delay
I don't see why this would be faster than 3s
buffering
slowComp
doesn't make it parallel
e
I expected it starts slowComp on 1 sees delay moves to next val 2 then starts its delay etc
Im simulating IO bound task not cpu bound
o
that's not how coroutines work
e
thats why I was expectiong it should take less than 3 sec
o
coroutines are essentially just like regular functions, except that you can choose to suspend them at a point, and it will remove it from the thread
it doesn't change the order of execution
e
So delay is same as spin wait ?
When I read docs my impression was different
o
it's not the same as, but it will not proceed to the next line of code until it is done
delay
will remove your coroutine from the thread, unlike a spin-wait which will block on the thread
additionally,
delay
will use some sort of timer to determine when to resume your coroutine, e.g.
ScheduledExecutorService
e
What do I need for the behaviour that I want, apart from futures ofc
o
something like this in `measureTimeMillis`:
Copy code
flow {
  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 process
there are other ideas in that issue
e
thx for the help, ill check the link
t
collect
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