首页 > 解决方案 > 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, ...).

标签: androidkotlinkotlin-flow

解决方案


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)
}

推荐阅读