sometimes, the usage of these four RxJs operators is a bit tricky, as they work almost the same way by merging different Observables inputs into only one output, to understand easily the difference between 'em all I've prepared some examples that show the difference of the outputs.If you have questions, suggestions or something not clear, feel free to comment with your question and I'll be glad to answer it.
ZIP Each time the zipped observables (or subjects) emit all of their values, the ZIP operator emits one time an array of all observables values.
// zip the 2 observables:zip(shapes$,cards$).subscribe(console.log);// then next data as:shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');// no need to complete the observables, it will output:["β οΈ","π"]["β€","1οΈβ£"]["β οΈ","π"]["β€","1οΈβ£"]
forkedJoin emits an array of the last values emitted by the observables (or the subjects) being forkJoined only after completing the stream of the observables (or the subjects).
// forkJoin the 2 observables:forkJoin(shapes$,cards$).subscribe(console.log);// then next data as:shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');// emits only when observable completed:shapes$.complete();cards$.complete();// outputs:["β€","1οΈβ£"]
combineLatest each time an observable (or a subject) emits a new value the combineLatest operator emits a new array of values (from all the observables passed to the combineLatest operator) containing the new value.
// combineLatest the 2 observables:combineLatest(shapes$,cards$).subscribe(console.log);// then next data as:shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');// no need to complete the observables, it will output:["β οΈ","π"]["β€","π"]["β€","1οΈβ£"]["β οΈ","1οΈβ£"]["β οΈ","π"]["β€","π"]["β€","1οΈβ£"]
withLatestFrom emits an array of both values, the main observable value, and the other observable last value being withLatestFromed.
// withLatestFrom the 2 observables:shapes$.pipe(withLatestFrom(cards$)).subscribe(console.log);// then next data as:shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');shapes$.next('β οΈ');cards$.next('π');shapes$.next('β€');cards$.next('1οΈβ£');// no need to complete the observables, it will output:["β€","π"]["β οΈ","1οΈβ£"]["β€","π"]
In case you want to play with these operators stackblitz here.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)