https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

ec

05/10/2020, 4:15 PM
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

octylFractal

05/10/2020, 4:16 PM
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

ec

05/10/2020, 4:19 PM
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

octylFractal

05/10/2020, 4:19 PM
that's not how coroutines work
e

ec

05/10/2020, 4:20 PM
thats why I was expectiong it should take less than 3 sec
o

octylFractal

05/10/2020, 4:20 PM
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

ec

05/10/2020, 4:21 PM
So delay is same as spin wait ?
When I read docs my impression was different
o

octylFractal

05/10/2020, 4:21 PM
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

ec

05/10/2020, 4:22 PM
What do I need for the behaviour that I want, apart from futures ofc
o

octylFractal

05/10/2020, 4:27 PM
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

ec

05/10/2020, 4:30 PM
thx for the help, ill check the link
t

thana

05/10/2020, 5:25 PM
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
4 Views