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

Lukas Lechner

07/12/2022, 10:59 AM
Hi! I have a question regarding flows. I want to use something like
Copy code
.buffer(capacity = 0, onBufferOverflow = BufferOverflow.DROP_LATEST)
in my flow, but this doesn't work, since a capacity of
1
is used when using
BufferOverflow.DROP_LATEST
. What's the use case: The upstream flow items are produced whenever the user clicks a button to perform a network request, which happens downstream after the buffer. When the user presses the button while the network request is on-going, this event should be dropped (that's why I am using a buffer with capacity of 0). However I am not able to achieve this. A new network request is initiated shortly after the previous one is complete when the user clicks the button while the first network request is currently running. Any idea on how to implement this in a nice way?
s

Sam

07/12/2022, 11:07 AM
Have you looked at
.conflate()
?
l

Lukas Lechner

07/12/2022, 11:09 AM
Yes, same behavior, since
.conflate()
also uses a buffer of capacaty = 1
n

Nick Allen

07/12/2022, 4:20 PM
Sounds like you maybe you want
collectLatest
or
mapLatest
?
l

Lukas Lechner

07/13/2022, 9:23 AM
Hmm, but this would cancel the network request and start a new one, right?
👍 1
n

Nick Allen

07/13/2022, 3:58 PM
idk how I misread that 🤦. You can use a
Channel
directly with capacity 0 and
trySend
to it. The danger here is that you can miss a first element if the collector is not setup first. https://pl.kotl.in/roLERBgwB
3 Views