forkjoin rxjs
If you are confused about the differences between forkJoin
, zip
, combineLatest
and withLatestFrom
, you are not alone! :)
如果您对forkJoin
, zip
, combineLatest
和withLatestFrom
之间的差异感到困惑,那么您并不孤单! :)
These 4 operators are what we know as
combination operators
- we use them when we need to join information from multiple observables.这4个运算子是
combination operators
-当我们需要连接来自多个观测器的信息时,我们使用它们。
我应该使用哪个运营商? (Which operator should I use?)
That is what this article is for! We will talk about the usage and differences between these 4 operators in an easy to understand way, so you know which one to choose when the time comes.
这就是本文的目的! 我们将以一种易于理解的方式来讨论这4个运算符之间的用法和差异,以便您了解何时可以选择哪个。
建立 ( Setup )
Imagine you are printing t-shirts. Ms. Color holds the color
information and Mr. Logo holds the logo
information. Both of them will pick color
and logo
spontaneously. You will need to wait and combine these two information continuously in order to print t-shirts. Ms. Color and Mr. Logo represent two observables in our code - color$
and logo$
.
想象一下您正在印刷T恤 。 Color女士保存color
信息,Logo先生保存logo
信息。 他们俩都会自发选择color
和logo
。 您将需要等待并连续地合并这两个信息才能打印T恤。 Color女士和Logo先生代表我们代码中的两个可观察对象-color color$
和logo$
。
// 0. Import Rxjs operators
import {
forkJoin, zip, combineLatest, Subject } from 'rxjs';
import {
withLatestFrom, take, first } from 'rxjs/operators';
// 1. Define shirt color and logo options
type Color = 'white' | 'green' | 'red' | 'blue';
type Logo = 'fish' | 'dog' | 'bird' | 'cow';
// 2. Create the two persons - color and logo observables,
// They will communicate with us later (when we subscribe)
const color$ = new Subject<Color>();
const logo$ = new Subject<Logo>();
// 3. We are ready to start printing shirt. Need to subscribe to color and logo observables to produce shirts, we will write code here later
...
// 4. The two persons(observables) are doing their job, picking color and logo
color$.next('white');
logo$.next('fish');
color$.next('green');
logo$.next('dog');
color$.next('red');
logo$.next('bird');
color$.next('blue');
// 5. When the two persons(observables) has no more info, they said bye bye.. We will write code here later
...
I guess the code above is pretty expressive itself. We created two observables by using Subject. For part 4 in the code, every .next(<value>)
means Ms. Color or Mr. Logo is picking color or logo.
我猜上面的代码本身就很具有表现力。 我们使用Subject创建了两个可观察对象。 对于代码的第4部分,每个.next(<value>)
表示Color女士或Logo先生正在选择颜色或徽标。
Take note of the sequence of information (part 4 in our code), here is the summary:-
注意信息的顺序(代码的第4部分),以下是摘要:
![sequence of info](https://scotch-res.cloudinary.com/image/upload/w_auto,q_auto:good,f_auto/media/272/6C1OMCYRQwm2puCgTyXf_sequence.gif)