BehaviorSubject'分组'

时间:2015-08-30 20:19:08

标签: rxjs

我刚刚开始使用RXJS来查看它是否可以取代我当前的手动数据流。我试图移植的一件事是记住流中最后一个值被记住的情况,因此未来的观察者总会得到当前的信息。价值以及随后的价值。这似乎是由BehaviorSubject实现的。

但是,我需要为一组实体执行此操作。例如,我可能有代表用户消息的数据:

{ userId: 1, message: "Hello!" }

我想要一个类似于BehaviorSubject的对象,它将为所有用户存储最后一条消息。这是我可以用开箱即用的RXJS做的事情,还是我需要自己做? (如果是这样,任何指针都会受到赞赏)。

编辑:经过一番思考之后,拥有一个“传入”的音乐似乎也是合乎逻辑的。 subject,一个更新Map的观察者,然后是一个我可以调用的函数,它从map值中初始化一个Observable,并与传入的流合并......?

1 个答案:

答案 0 :(得分:0)

我使用RxJS和类似redux的状态设置。我有一个BehaviorSubject,它保存当前状态,每次触发事件/动作时,当前状态通过生成新状态的函数传递,主体订阅了该状态。

以下是我使用的简化版本:

export default class Flux {

  constructor(state) {
    //all resources are saved here for disposal (for example, when hot loading)
    //this is just a flux dispatcher
    this.dispatcher = new rx.Subject(),
    // BehaviorSuject constructed with initial state
    this.state = new Rx.BehaviorSubject(state),
  }

  addStore(store, initialState, feature = store.feature) {
      this.dispatcher
        .share()
        // this is where the "reduction" happens. store is a reducer that 
        // takes an existing state and returns the new state
        .flatMap(({action, payload}) =>
            store(this.state.getValue(), action, payload))
        .startWith(initialState || {})
        .subscribe(this.state)
    );

    return this;
  }

  addActions(actions: rx.Subject) {
    // actions are fed to the dispatcher
    this.resources.push(actions.share().subscribe(this.dispatcher));
    return this;
  }

}

我创建了一个具有管理状态的全局Flux对象。然后,对于每个“功能”或“页面”或任何我希望我添加动作和商店。它使管理状态变得非常容易,而像时间旅行这样的东西是Rx给出的东西。

相关问题