不调用带有ReplaySubject的forkJoin.subscribe

时间:2019-05-14 13:58:39

标签: javascript rxjs

我想创建一个Observable,如果两个ReplaySubject实例都持有一个值,则将触发它。我这样尝试过:

StatusBarNotification

同时调用let v1 = new Rx.ReplaySubject(); let v2 = new Rx.ReplaySubject(); v1.next('X'); const combo = Rx.Observable.forkJoin(v1, v2) combo.subscribe( arr => console.log(arr) ) v1.subscribe( s => console.log('v1', s) ); v2.subscribe( s => console.log('v2', s) ); v2.next('Y'); v1.subscribe,但不调用v2.subscribe。我怎么了如何解决此问题?

2 个答案:

答案 0 :(得分:2)

forkJoin等待输入可观察值完成,然后发出最后发出的项。您必须完成两个主题。

答案 1 :(得分:2)

forkJoin将仅在输入可观察值全部完成后才发出所有最后一个值的数组。如果您手动完成v1v2,则combo将发出:

let v1 = new rxjs.ReplaySubject();
let v2 = new rxjs.ReplaySubject();

v1.next('X');
v2.next('Y');
v2.next('Z'); // This additional value should demonstrate the idea of forkJoin

const combo = rxjs.forkJoin(v1, v2)
combo.subscribe( arr => console.log(arr) )

v1.complete();
v2.complete();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

如果您不希望内部观察对象完成操作,则可能会寻找combineLatest

let v1 = new rxjs.ReplaySubject();
let v2 = new rxjs.ReplaySubject();

v1.next('X');
v2.next('Y');

const combo = rxjs.combineLatest(v1, v2)
combo.subscribe( arr => console.log(arr) )
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>