[RxJS] Replace zip with combineLatest when combining sources of data

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Replace zip with combineLatest when combining sources of data相关的知识,希望对你有一定的参考价值。

This lesson will highlight the true purpose of the zip operator, and how uncommon its use cases are. In its place, we will learn how to use the combineLatest operator.

const length$ = Rx.Observable.of(5, 4);
const width$ = Rx.Observable.of(7,1);
const height$ = Rx.Observable.of(2.8, 2.5);

const volume$ = Rx.Observable
  .zip(length$, width$, height$,
    (length, width, height) => length * width * height
  );

volume$.subscribe(function (volume) {
  console.log(volume); 
});

zip requiers each observable has synchronized emissions.  It means:

const length$ = Rx.Observable.of(5);
const width$ = Rx.Observable.of(7);
const height$ = Rx.Observable.of(2.8, 2.5);

2.5 won‘t be calculated only when lenth$ and width$ provide second value.

 

In this case we can use combineLatest instead of zip:

const length$ = Rx.Observable.of(5);
const width$ = Rx.Observable.of(7);
const height$ = Rx.Observable.of(2.8, 2.5);

const volume$ = Rx.Observable
  .combineLatest(length$, width$, height$,
    (length, width, height) => length * width * height
  );

volume$.subscribe(function (volume) {
  console.log(volume); 
});

 

以上是关于[RxJS] Replace zip with combineLatest when combining sources of data的主要内容,如果未能解决你的问题,请参考以下文章

[RxJS] Split an RxJS Observable into groups with groupBy

[RxJS] Combination operator: zip

[RxJS] Reactive Programming - Using cached network data with RxJS -- withLatestFrom()

[RxJS] Flatten a higher order observable with mergeAll in RxJS

[RxJS] Flatten a higher order observable with concatAll in RxJS

Observable.zip 不是函数