preface

ForkJoin, zip, combineLatest are RXJS merge operators used to merge multiple streams. Many people don’t know the difference between them, which is perfectly normal, because in practice most merged streams are streams that send data once and then close (such as HTTP requests), and there is no difference between the three operators in terms of results.

When did the difference appear? The difference is only apparent if the stream it operates on emits data multiple times. For ease of understanding, the next stream lifecycle is next, complte, error; “Next” is used when launching data, “complete” is used when launching data, and “error” is used when launching error. Both event “complete” and “error” indicate the end of the life cycle

case

import { interval, combineLatest, forkJoin, zip } from 'rxjs'; 
import { delay, take } from 'rxjs/operators';


const a = interval(1000).pipe(
 take(2) ); const b = interval(1000).pipe(  delay(1000),take(2) ); const c = interval(1000).pipe(  delay(3000), take(5) ); combineLatest(a, b, c).subscribe(res= > console.log(res)) / / [1, 1, 0] / / [1, 1, 1) / / [1, 1, 2] / / [1, 1, 3] / / (1, 1, 4] zip(a, b, c).subscribe(res= > console.log(res)) / / [0, 0, 0] / / [1, 1, 1) forkJoin(a, b, c).subscribe(res= > console.log(res)) / / (1, 1, 4] Copy the code

forkJoin

ForkJoin emits one and only one data at the end of each merged stream, as follows: 1 data at 2 seconds for forkJoin, 1 data at 3 seconds for B, 4 data at 8 seconds for C, and 8 seconds for forkJoin.

zip

Returns the first data for each of the merged streams, as many times as the index is the same, a and b have the index 0,1; The index of C has 0, 1, 2, 3, 4, so there are only 0 and 1 similarities, so there are only two data returns. The first one is [0, 0, 0] at 4 seconds, and the second one is [1,1,1] at 5 seconds. After that, both A and B end the stream, so there is no data

combineLatest

Will wait after each child stream launch your first data, returns the data for the first time, to merge data is take its latest emission data merged, any words flow after launch new data, no longer wait for the other child flow synchronous firing data, but instead USES other streams to merge the latest data, before the above code, when c to get the data for the first time, A and B both send data twice and end the stream. The first data is [1, 1, 0] after all integration, and then C sends the second data (a and B do not send data) and returns [1, 1, 1], and so on until C sends the last data and returns [1.1.4].

The difference between

ForkJoin takes the data for the last time only with zip wait takes the data for the first time, and combineLatest takes the data once as soon as the data is emitted

Online code sample

If there are any mistakes in this article, please correct them in the comments section. If this article has helped you, please like it and follow it

This article is formatted using MDNICE