Hi. I used channels to transfer data from one appl...
# coroutines
g
Hi. I used channels to transfer data from one application point to another (From one screen to another). When I call send and receive for the first time, everything works fine, but if I try to re-do send for the same channel, I can’t get the data by calling the receive method. I found a solution that needs to use consumeEach. And the truth is, if you use it, then when you re-send, the receive method returns new data. In this regard, the question is, what is the fundamental difference of consumeEach from other functions: consume, first, last and others. I give an example code
d
Copy code
/**
 * Returns first element.
 * @throws [NoSuchElementException] if the channel is empty.
 *
 * The operation is _terminal_.
 * This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
 *
 * **Note: This API will become obsolete in future updates with introduction of lazy asynchronous streams.**
 *           See [issue #254](<https://github.com/Kotlin/kotlinx.coroutines/issues/254>).
 */
Short version is
first
calls
consume
z
you want to avoid closing the channel
which
.first()
will do
so future sends/offers to that channel won’t be received
it’s unfortunate that receivers of data can close the channel
g
@zak.taccardi But consumeEach close the channel too. Why
consumeEach
work,
first
doesn’t work. I don’t understand
@danny Yea, I known, but
consumeEach
work,
first
doesn’t work.
d
first/last/others all use
consume
, so they cancel the channel -
consumeEach
iterates over the channel, so won't return until the channel is closed/cancelled
z
use
for( item in channel)
to avoid closing the channel on unsubscription
g
@zak.taccardi Hm….. I always send only one number. If use
for( item in channel)
this, it will be at least strange to do a search from a single element.
Maybe there is another way to apply events?
u
Just use receive
g
@uli
receive
not get result when channel out of capacity. my capacity equal 1.
d
*capacity you mean?
g
@Daniel Tam yes
u
So you write more then you consume?
z
Use an unlimited capacity then
u
You write you always send one number only. So capacity of one should never get exceeded
👍 1