hi everyone, I am trying to use the `produce` meth...
# coroutines
f
hi everyone, I am trying to use the
produce
method to create a channel inside a suspending method but I have some problems. I have a different behaviour defining my method as
CoroutineScope
extension method and using
coroutineScope
inside a suspending method. These are the two versions:
Copy code
private fun CoroutineScope.produceExtension(): ReceiveChannel<Int> = produce {
    send(1)
    send(2)
    send(3)
}

private suspend fun produceCoroutineScope(): ReceiveChannel<Int> = coroutineScope {
    produce {
        send(1)
        send(2)
        send(3)
    }
}
`
Using the second method I am not able to use the channel (the method never ends), I have already opened an issue with the complete code here https://github.com/Kotlin/kotlinx.coroutines/issues/645 Am I doing something wrong? Should the two methods be equivalent?
g
Better report to kotlinx.coroutines repo https://github.com/Kotlin/kotlinx.coroutines/issues
f
thanks, I’ll open an issue there as well
g
Why do you use suspend function and why do you need coroutineScope in this case?
f
it’s because I’d like to define that method in another class so I can’t define it as extension function
and I want to use the non deprecated version of
produce
method defined in
CoroutineScope
g
Oh, I see, new produce
Not sure why itt doesn’t emit events, but instead you should pass scope there to connect to existing coroutine scope
or create CoroutineScope using parent context: CoroutineScope(coroutineContext) nope, this doesn’t work
f
you are right, passing the scope as parameter works but I’d like to avoid passing it on all the methods
g
But this is the way how you cannect async code to your scope
f
are you sure? Isn’t the
coroutineScope
method another valid way of doing it?
k
The second doesn’t work as expected probably because
coroutineScope
will suspend until the producer is closed, which doesn’t happen in this example 🤔 Anyway though, you could define it as extension function in another class and execute like so:
Copy code
with(anotherClassInstance) {
  produceExtension()
}
assuming this is already within a coroutine scope
f
even adding a
close
invocation I have the same problem (and I’d like to consume the values before the channel is closed)
I wasn’t aware of that syntax, thanks for pointing it out 🙂
however I still think that the two methods should do the same thing
g
Yeah, Kingsley right, this is because produce coroutineScope suspended
No, they do not do the same in this case, because now coroutineScope alwys waits for child coroutine
We need extension functions with multiple receivers!
2
f
ok, I haven’t read that comment
so, probably I can use the
with
method until they define the integration of channels with structured concurrency