在rxjs中组合BehaviorSubjects

时间:2018-11-07 19:36:10

标签: rxjs

我想将两个BehaviorSubjects与CombineLatest()结合在一起。但是,这会产生一个普通的Observer,对于我的情况不起作用,因为我需要一个广播流,该广播流在侦听时会发出以前的值。

如何将多个BehaviorSubject合并为一个BehaviorSubject?

1 个答案:

答案 0 :(得分:0)

如果我是您,我将创建一个单独的BehaviorSubject,该行为可以从主要两个排放源收集排放并重新排放它们或提供值:

bs1 = new BehaviorSubject(1);
bs2 = new BehaviorSubject(2);
bsCombined = new BehaviorSubject(undefined);

bs1.subscribe(val => bsCombined.next(val));
bs2.subscribe(val => bsCombined.next(val));

bsCombined.subscribe(newestVal => {
   if(newestVal !== undefined) {
     /* Go on with processing */
   }
})
/* Due to previous subscriptions those emissions will be stored in combined behaviorSubject */
bs1.next(2);
bs1.next(3);
bs2.next(6);
bs1.next(4);