我需要处理流收集中的当前值和先前值,因此我需要一些类似这样的运算符:
----A----------B-------C-----|--->
---(null+A)---(A+B)---(B+C)--|--->
一个想法是这样的:
fun <T: Any> Flow<T>.withPrevious(): Flow<Pair<T?, T>> = flow {
var prev: T? = null
this@withPrevious.collect {
emit(prev to it)
prev = it
}
}
但是这样就无法控制执行第一个流程的上下文。有没有更灵活的方案?
最佳答案
Flow
是顺序的,因此您可以使用变量来存储先前的值:
coroutineScope.launch {
var prevValue = null
flow.collect { newValue ->
// use prevValue and newValue here
...
// update prevValue
prevValue = newValue
}
}
关于kotlin - 在流的收集中获取当前和以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72626286/