获取流程中的最新和先前的值
我需要处理流程收集中的当前和以前的值,因此我需要一些这样的运算符:
----A----------B-------C-----|--->
---(null+A)---(A+B)---(B+C)--|--->
一个想法是类似的:
fun <T: Any> Flow<T>.withPrevious(): Flow<Pair<T?, T>> = flow {
var prev: T? = null
[email protected] {
emit(prev to it)
prev = it
}
}
但是,这种方式无法控制第一个流的上下文。有更灵活的解决方案吗?
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
[email protected] {
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
There's an operator which makes this very easy:
runningFold
可能需要调整无效以适合您的用途酶
您 显性
There's an operator which makes this very easy:
runningFold
The docs have an example on how to use it to collect each emission of a flow; this can be easily adapted to fit our needs
You might need to tweak nullabilities to fit your usecase
You can also replace the
History
class in with aPair
in case you value brevity over explicitnessFlow
是顺序的,因此您可以使用变量存储上一个值:Flow
s are sequential, so you can use a variable to store the previous value:我认为您可以使用
RunningFold
非常轻松地做到这一点,因为使用它,您可以使用折叠操作将流动转换为另一个流程。 IS是因为RunningFold
确实将所有内容都折叠成一个值,例如fold
。取而代之的是,它在作为所有突变的历史上工作之间保持了所有步骤。您唯一需要关注的是,每个返回的值必须是一对,第一个值必须为null,并且第一对必须允许左值中的null。允许null作为蓄能器,还意味着必须将该值滤出。粗略地,您需要遵循这样的示例:
这样,您就不需要创建运营商类型,因为您的运营商类已经是
Pair Pair
类。您可以使用
fold
等测试差异:结帐有关折叠的更多信息以及此处的不同形式:
fold
I think you can make this very easily with
runningFold
, because with it, you can transform a flow into another using a fold operation. The is becauserunningFold
does fold everything into one value likefold
. Instead, it keeps all steps in between working as a history of all mutations. The only thing you need to be concerned with is that every returned value must be a pair, the first value must be null and the first pair must allow a null in the left value. Allowing a null as the accumulator means also that this value must be filtered out.Roughly, you'll need to follow an example like this one:
This way you won't be needing to create a carrier class type, because your carrier class is already the
Pair
class.You can test the difference with
fold
like this:Checkout more information about fold and different forms of it here:
fold
runningFold
kotlin.collections