首页 文章

BehaviorSubject 'grouped'

提问于
浏览
0

我刚刚开始使用RXJS来查看它是否可以取代我当前的手动数据流 . 我试图移植的一件事是记住流中最后一个值的情况,因此未来的观察者将始终获得“当前”值以及后续值 . 这似乎是由BehaviorSubject完成的 .

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

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

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

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

1 回答

  • 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给出的 .

相关问题