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

dimsuz

08/16/2022, 11:05 AM
If I have a
Flow<Int>
, say 1, 20, 30, 35, how could I produce a flow which "samples" this flow and counts the difference between last elements emitted in chunked time windows? for example sampleTime=20ms if
1,20, 30
got emitted in 20ms since start and then only one item
35
got emitted in next 20 ms, I would get
29,5
(
30-1,35-30
) out. Should I combine sample with map with timestamps? Would be grateful for direction. Or should I write a fully custom "transform" function instead of trying to combine existing ones?
b

bezrukov

08/16/2022, 11:38 AM
I feel built-in
sample
fun does almost what you want, except calculating the diff in the first window, but you can wrap it to onEach+drop(1) to take the first value into a separate window. But in this case it won't emit anything if original flow contains only a single element. Technically, you need https://github.com/Kotlin/kotlinx.coroutines/issues/1302 chunked with timeout + scan over it
d

dimsuz

08/16/2022, 12:07 PM
Yep, I felt like "scan" also should come into play here. Thanks, I'll play with this!
3 Views