Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two observable arrays into a single array?

example:

var s1 = Observable.of([1, 2, 3]);

var s2 = Observable.of([4, 5, 6]);

s1.merge(s2).subscribe(val => {
   console.log(val);
})

I want to get [1,2,3,4,5,6]

instead of

[1,2,3]

[4,5,6]

like image 562
Wayn Chaw Avatar asked May 23 '17 17:05

Wayn Chaw


People also ask

How do I combine multiple Observables into one?

We can use the concat operator to take multiple Observables and return a new Observable that sequentially emits values from each Observable that were passed in. It works by subscribing to them one at a time and merging the results in the output Observable.

What is Observable array?

ObservableArray is an array that allows listeners to track changes when they occur.


2 Answers

forkJoin works wells, you just need to flatten the array of arrays :

const { Observable } = Rx;

const s1$ = Observable.of([1, 2, 3]);
const s2$ = Observable.of([4, 5, 6]);

Observable
  .forkJoin(s1$, s2$)
  .map(([s1, s2]) => [...s1, ...s2])
  .do(console.log)
  .subscribe();

Output : [1, 2, 3, 4, 5, 6]

Plunkr to demo : https://plnkr.co/edit/zah5XgErUmFAlMZZEu0k?p=preview

like image 133
maxime1992 Avatar answered Sep 17 '22 11:09

maxime1992


My take is zip and map with Array.prototype.concat():

https://stackblitz.com/edit/rxjs-pkt9wv?embed=1&file=index.ts

import { zip, of } from 'rxjs';
import { map } from 'rxjs/operators';

const s1$ = of([1, 2, 3]);
const s2$ = of([4, 5, 6]);
const s3$ = of([7, 8, 9]);
...

zip(s1$, s2$, s3$, ...)
  .pipe(
    map(res => [].concat(...res)),
    map(res => res.sort())
  )
  .subscribe(res => console.log(res));

like image 30
Oliver Sahner Avatar answered Sep 17 '22 11:09

Oliver Sahner