简体   繁体   English

获取流集合中的当前值和上一个值

[英]Get current and previous value in flow's collect

I need to handle current and previous value in flow collect, so I need some operator that acts like that:我需要处理流收集中的当前值和以前的值,所以我需要一些这样的操作符:

----A----------B-------C-----|--->

---(null+A)---(A+B)---(B+C)--|--->

One idea is something like:一个想法是这样的:

fun <T: Any> Flow<T>.withPrevious(): Flow<Pair<T?, T>> = flow {
    var prev: T? = null
    this@withPrevious.collect {
        emit(prev to it)
        prev = it
    }
}

But this way there is no control over a context in which first flow will be executed.但是这种方式无法控制将执行第一个流程的上下文。 Is there more flexible solution?有更灵活的解决方案吗?

Flow s are sequential, so you can use a variable to store the previous value: Flow是顺序的,因此您可以使用变量来存储先前的值:

coroutineScope.launch {
    var prevValue = null
    flow.collect { newValue ->
        // use prevValue and newValue here
        ...
        // update prevValue
        prevValue = newValue
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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