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

goldin

12/10/2018, 10:27 PM
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

danny

12/10/2018, 10:30 PM
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

zak.taccardi

12/10/2018, 10:34 PM
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

goldin

12/10/2018, 10:40 PM
@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

danny

12/10/2018, 10:50 PM
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

zak.taccardi

12/10/2018, 10:51 PM
use
for( item in channel)
to avoid closing the channel on unsubscription
g

goldin

12/10/2018, 11:22 PM
@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

uli

12/11/2018, 5:38 AM
Just use receive
g

goldin

12/11/2018, 7:02 AM
@uli
receive
not get result when channel out of capacity. my capacity equal 1.
d

Daniel Tam

12/11/2018, 1:27 PM
*capacity you mean?
g

goldin

12/11/2018, 1:48 PM
@Daniel Tam yes
u

uli

12/11/2018, 6:45 PM
So you write more then you consume?
z

zak.taccardi

12/11/2018, 6:45 PM
Use an unlimited capacity then
u

uli

12/11/2018, 6:46 PM
You write you always send one number only. So capacity of one should never get exceeded
👍 1
3 Views