基于另一个Observable的自定义过滤器的功能反应运算符 [英] Functional reactive operator for custom filter based on another Observable

查看:60
本文介绍了基于另一个Observable的自定义过滤器的功能反应运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了好玩和学习,我正在尝试使用功能性反应式编程在我的应用程序中实现撤消系统。我有一个状态更改流,需要保存到撤消堆栈中。当用户单击undo时,我从堆栈中获取一个值并相应地更新应用程序状态。

For fun and to learn I'm trying to implement an undo system in my app using functional reactive programming. I have a stream of state changes, which need to be saved onto the undo stack. When the user clicks undo, I take a value from the stack and update application state accordingly.

问题是此更新本身也会在状态更改流中生成一个事件。所以我想要的是从状态变化中导出另一个流,它在撤消后立即省略状态变化。

The problem is that this update itself also generates an event in the state change stream. So what I would like is to derive another stream from state changes, which ommits state change right after undo.

一个简单的图表:

states   ----S----S----S----
undos    -------U-----------     
save     ----S---------S----

第一行是应用程序状态更改流,第二行是用户触发的撤消事件,第三行是我想要实现和监听的流第一个流。

The first line is the stream of application state changes, the second line are undo events triggered by the user and the third line is the stream I'd like to implement and listen to instead of the first stream.

在FRP中表达此类意图的最佳方式是什么?

What is the best way to express such intent in FRP?

推荐答案

在RxJS中:

var state = Rx.Observable.interval(2000)
  .map(s => ({type:'s', value: s}))
  .take(3);
var undo = Rx.Observable.interval(3000)
  .map(u => ({type:'u', value: u}; }))
  .take(1);

var save = state.merge(undo).scan((prev, curr) =>
  if (prev.type === 'u') {
    return {type: 'removed'};
  } else {
    return curr;
  }
}).filter(x => x.type !== 'removed' && x.type !== 'u');

请参阅 JSBin 。诀窍是 merge 是一个垂直组合器(垂直于流图), scan 是一个水平组合器。使用两者,首先合并,然后扫描,您可以构建更强大的组合器,如解决您的问题的组合器。 Bacon和Kefir的解决方案类似。

See this JSBin. The trick is merge is a vertical combinator (vertical with regards to the streams diagram), and scan is a horizontal combinator. Using both, first merge, then scan, you are able to build more powerful combinators like the one that solves your problem. The solution is similar in Bacon and Kefir.

这篇关于基于另一个Observable的自定义过滤器的功能反应运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆