There really is no way to avoid passing the channe...
# coroutines
c
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
not if you don't want it to take a
CoroutineScope
c
Umm I don't see it
o
what do you mean?
c
How could you do it passing a coroutinescope?
o
you would basically re-implement
produce
a
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
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
Oh I see, that's clever. Thank you guys
It was out of curiosity anyways, I'm gonna use produce 😂
a
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
you understand how
coroutineScope
works, right? it suspends until all child coroutines complete, which includes
produce
a
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
well, it's technically a different scope, the scope of whatever's calling the function
a
true, instead of being a child scope