Observable.zip 但获取第一个值,不要等待所有值

Observable.zip but get first value, don't wait for all values

假设我有这个:

const a = new BehaviorSubject(0);
const b = new BehaviorSubject(0);

Observable.zip(
    a.asObservable(),
    b.asObservable()
)
.subscribe(v => {
    // this will fire with [0,0]
    // but I want it to also fire with [1,0]
});

a.next(1);

如何在订阅下一个功能中实现评论中的内容? 我相信我需要找到一个不同于 Observable.zip() 的运算符,比如 Observable.first().

.zip() 仅当 observables 的排放量是可压缩的时才有效。对于您的情况,因为 0,0 已经压缩,因此只会有一个这样的发射。如果您想进行下一次发射,您的 b 主题也必须发射一个值:

const a = new BehaviorSubject(0);
const b = new BehaviorSubject(0);

Observable.zip(
    a.asObservable(),
    b.asObservable()
)
    .subscribe(v => {
        // this will fire with [0,0]
        // will fire only if both a and b has emisions. 
        // this also logs [1,1] because there is a b.next(1)
    });

a.next(1);
b.next(1); // this step is crucial

如果要检测任意数量的 Observables 组合的任何变化,则必须使用 Observable.combineLatest().

The CombineLatest operator behaves in a similar way to Zip, but while Zip emits items only when each of the zipped source Observables have emitted a previously unzipped item, CombineLatest emits an item whenever any of the source Observables emits an item (so long as each of the source Observables has emitted at least one item). When any of the source Observables emits an item, CombineLatest combines the most recently emitted items from each of the other source Observables, using a function you provide, and emits the return value from that function.