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

Carrascado

08/26/2020, 6:43 PM
There really is no way to avoid passing the channel as an argument and avoid
produce
? I don't want to avoid produce, it's just for curiosity
o

octylFractal

08/26/2020, 6:44 PM
not if you don't want it to take a
CoroutineScope
c

Carrascado

08/26/2020, 6:45 PM
Umm I don't see it
o

octylFractal

08/26/2020, 6:46 PM
what do you mean?
c

Carrascado

08/26/2020, 6:46 PM
How could you do it passing a coroutinescope?
o

octylFractal

08/26/2020, 6:48 PM
you would basically re-implement
produce
a

Andrea Giuliano

08/26/2020, 6:48 PM
I believe the only limitation with that is that it’s valid when you have a single coroutine that is producing multiple values. If instead you have multiple coroutines producing values and you want to collect them all then I guess using channels is fine
o

octylFractal

08/26/2020, 6:49 PM
Copy code
fun CoroutineScope.produceSquares(): ReceiveChannel<Int> {
  val channel = Channel<Int>()
  launch {
      for (x in 1..5) channel.send(x * x)
      channel.close()
  }
  return channel
}
there it is without produce, but it's way less safe than what
produce
gives you
c

Carrascado

08/26/2020, 6:51 PM
Oh I see, that's clever. Thank you guys
It was out of curiosity anyways, I'm gonna use produce 😂
a

Andrea Giuliano

08/26/2020, 7:04 PM
it’s interesting though how, if you change the example code to this
Copy code
suspend fun produceSquares(): ReceiveChannel<Int> = coroutineScope {
        produce {
            for (x in 1..5) {
                send(x * x)
            }
        }
    }
so in practice you are not making
produceSquare
an extension function for
CoroutineScope
the code blocks after sending the first item in the channel. As if in the original example the channel gets created with the right side while in this snippet it gets created with 0 capacity? Anyone knows why?
o

octylFractal

08/26/2020, 7:05 PM
you understand how
coroutineScope
works, right? it suspends until all child coroutines complete, which includes
produce
a

Andrea Giuliano

08/26/2020, 7:05 PM
right! I always forget that! 😄
that’s interesting though, so if you make an extension function of CoroutineScope, you remove the waiting part and the coroutines gets launched still in the same scope, but the function won’t wait.. interesting..
o

octylFractal

08/26/2020, 7:09 PM
well, it's technically a different scope, the scope of whatever's calling the function
a

Andrea Giuliano

08/26/2020, 7:09 PM
true, instead of being a child scope
7 Views