简体   繁体   中英

How to create a flow which detects consecutive value increments of another flow?

I have a hot flow fooFlow that emits integer values. How can I construct another hot flow barFlow that only emits values when fooFlow emits a larger value than the most recent value emitted by fooFlow ? In a sense, barFlow detects consecutive value increases of fooFlow .

Example: If fooFlow emits (4, 2, 7, 3, 3, 1, 2, 4, ...), then barFlow emits (7, 2, 4, ...).

There might be a more natural or cleaner looking way to do this, but this is my first instinct:

val barFlow: SharedFlow<Int> = MutableSharedFlow<Int>().also { outflow ->
    var previousValue = Int.MAX_VALUE
    fooFlow.onEach { newValue ->
        if (newValue > previousValue) {
            outflow.emit(newValue)
        }
        previousValue = newValue
    }.launchIn(viewModelScope)
}

This is precisely what fold() can be used for:

val barFlow = fooFlow.fold(Int.MIN_VALUE) { maxValue, newValue ->
  max(maxValue, newValue)
}

It lets you set a initial value (here, Int.MIN_VALUE so that every value is greater than it), then gives you access to the previous value (the maxValue ) and the new value (the newValue ), allowing you to do whatever comparisons and use that output as the newly emitted value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM