如何使用 RxJS 对数据更改做出“反应”

How to "react" on data changes with RxJS?

本文关键字:反应 何使用 RxJS 数据      更新时间:2023-09-26

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

更具体的例子。假设我有一个名为 Widget 的小部件,Widget有一个标题和按钮。状态应包含标题和信息(如果已单击按钮)。从阅读 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) { ... });