如何使用 RxJS "react" 处理数据变化?

How to "react" on data changes with RxJS?

这里是 RxJS 初学者:我在使用 RxJS 保存和跟踪数据更改时遇到了问题。假设我在小型 views/widgets 中构建我的应用程序,并且每个 view/widget 都有自己的状态并且应该对数据更改进行操作。我该怎么做?

更具体的例子。假设我有一个名为 Widget 的小部件,并且 Widget 有一个标题和按钮。状态应包含标题和信息 if 按钮已被单击。从阅读 RxJS 的文档来看,这似乎是一个很好的起点:

var widgetState = new Rx.Subject().startWith({
  wasClicked: false,
  title: 'foo'
});

现在我想在某些数据更改时收到通知:

var widgetStateChanges = widgetState.subscribe(function(data) {
  console.log('data: ', data);
  // what do i do with the data here?
  // i would like to merge the new data into the old state
});

widgetStateChanges.onNext({ title: 'bar' });

我听到了变化,但我不知道如何保存它们。如果发生某些数据更改,我还想做一些特别的事情。像这样。

widgetStateChanges.filter(function(e) {
  return e.wasClicked;
}).do(function(e) {
  console.log('Do something because was clicked now.');
});

但是我不能filter订阅(widgetStateChanges),只能订阅主题(widgetState)。

使用 BehaviorSubject 跟踪可观察状态:

var widgetState = new Rx.BehaviorSubject({ wasClicked: false, title: 'foo' });

// change state, probably in response to UI events
// Note we always set the full state, not just the "delta"
widgetState.onNext({ wasClicked: true, title: 'foo2' });

// example listening to title input field and updating state
// assumes rxjs-jquery
$("#title").onAsObservable("change").subscribe (function (ev) {
    var oldState = widgetState.value;
    var newTitle = $("#title").val();
    // do not mutate the oldState object, instead clone it and change the title
    var newState = $.extend({}, oldState, { title: newTitle });

    // send the update
    widgetState.onNext(newState);
});

// listen to new state values, probably to update your HTML?
widgetState.subscribe(function (newState) { ... });

// listen only when wasClicked is true
widgetState
    .filter(function (s) { return s.wasClicked; })
    .subscribe(function (s) { ... });