Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between buffers in Kotlin flow

As far as I know there are three types of buffers in Kotlin flow: Buffer, Conflate and CollectLatest and I'm having trouble figuring out the differences between these three terminal operators.

flow.buffer().collect{...}
flow.collectLatest{...}
flow.conflate().collect{...}

I apologize the brevity, but what are the differences between these buffers and when should we use each of them?

Any help is appreciated in advance.

like image 480
AlirezA Barakati Avatar asked Aug 24 '26 23:08

AlirezA Barakati


1 Answers

Normally, emitting and collecting code runs sequentially, "emitter" emits new value after previous one collected somewhere. ("Collected" means terminal operator's lambda is finished). Buffering allows to run emitting code concurrently with collecting code.

buffer() allows emitter to emit new values while the old ones is still being processed (and saves them in buffer for later).

collectLatest() restarts its lambda on each new value collected, even if old one is still being processed.

conflate() operator skips intermediate values, which means that after processing the current value, collector collects only the most recent value received during processing previous one (same as buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST).

like image 125
bylazy Avatar answered Aug 26 '26 19:08

bylazy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!