How to concat two observable arrays into a single

2019-02-24 01:01发布

问题:

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]

回答1:

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



回答2:

Maybe you could do this with List instead of Array:

var s1 = Rx.Observable.of(1, 2, 3); 
var s2 = Rx.Observable.of(4, 5, 6); 

and then

Rx.Observable.merge(s1,s2).toArray().map(arr=>arr.sort()).su‌​scribe(x=>console.l‌​og(x))


回答3:

Just instead of Observable.of use Observable.from that takes as argument an array and reemits all its values:

var s1 = Observable.from([1, 2, 3]);
var s2 = Observable.from([4, 5, 6]);

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

Maybe instead of merge you might want to prefer concat but in this situation with plain arrays it'll give same results.

This will give you:

1
2
3
4
5
6

If you want this as a single array you could append also toArray() operator. Btw, you could achieve the same with Observable.of but you'd have to call it with Observable.of.call(...) which is probably unnecessary complicated and it's easier to use just Observable.from().