Skip to content Skip to sidebar Skip to footer

Merge Two Observables, Single Output

Hello guys I'm trying to grasp RxJS lib and the whole idea of reactive programming. I'm trying to merge two observables into one. First observable contains an array of objects Defe

Solution 1:

Merging observables means that items emitted by both observable will be emitted successively and separately by the new merged observable, cf this page. If your observables emit just one item each and you want the merge the items by concatenating the arrays, you could use the zip operator as follows:

zip(observable, this.observable)
  .pipe(map(x => x[0].concat(x[1])))
  .subscribe(data => console.log('merge', data))

More precisely zip(obsa, obsb) creates a new observable that listens to obsa and obsb, and after receiving itema from obsa and itemb from obsb emits the item x=[itema, itemb]. In your case x[0]=itema, x[1]=itemb are arrays and (x => x[0].concat(x[1])) concatenates these two arrays. Note that if obsa and obsb emit more than one array, the zipped observable will always wait to have one item from obsa and one from obsb before emitting a new [itema, itemb]. For the concat() method, cf this page.

And don't forget to import { zip } from 'rxjs' and import { map } from 'rxjs/operators'.


Post a Comment for "Merge Two Observables, Single Output"