How do I use `launch { send(..) }` in `produce {}`...
# coroutines
c
How do I use
launch { send(..) }
in
produce {}
and ensure I can receive them in
produce.consumeEach
?
Copy code
produce {
  list.forEach {
    coroutineScope {
      it.nestedList.forEach { sub ->
        launch { send(sub) }
      }
    }
  }
}.consumeEach { println(it) }
It seems that the channel has ended before all the data is send
j
Why don't you just
send
instead of
coroutinScope + launch + send
?
That being said, the above should code should work IMO. How exactly do you observe the behaviour you're getting?
Also, if you don't really need a channel, you could use
channelFlow
instead of
produce
to get a
Flow
instead, which may be more convenient to work with (but that may depend on your use case)
c
@Joffrey In fact, I need to initiate multiple network requests at the same time, and then I need to know that they are all completed. I don’t know what the best code for this use case is..
j
coroutineScope
+ mutiple nested
launch
(or maybe
async
if you want results) seems appropriate for that, but the example code above seemed to suggest you were sending elements from a list, so it would have been unnecessary. If you want to make concurrent network calls, this is correct. You just have to be careful about whether you're blocking any threads etc. If these calls are blocking you might want to dispatch them using
<http://Dispatchers.IO|Dispatchers.IO>
c
Thank you. In fact, I don’t know the principle of channel. Under what circumstances does channel complete the channel? Is it judged that it has not been call
send
for a long time to decide or something else? I asked this question because I found something missing in the result after running (it is determined that it was call
send
). I will try to restore a code to recover this error
j
In general, the channel should be explicitly closed with a call to
close()
on the producer side, but
produce
does it automatically at the end of the block when you reach it. Since you have put
coroutineScope
around your
launch
calls, they should all have finished by the time you reach the end of the block, so you should be fine. Maybe you had this error without
coroutineScope
?
Note that the channel created by
produce
would also automatically be closed if an exception is thrown somewhere in the
produce
block.
c
I will check the errors and try to read the decompiled code. Thank you!