如何将两个可观察数组连接成一个数组



example:

var s1 = Observable.of([1, 2, 3]);
var s2 = Observable.of([4, 5, 6]);
s1.merge(s2).subscribe(val => {
   console.log(val);
})

我想得到[1,2,3,4,5,6]

而不是

[1,2,3]

[4,5,6]

forkJoin工作得很好,你只需要扁平化数组:

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();

输出 : [1, 2, 3, 4, 5, 6]

Plunkr演示:https://plnkr.co/edit/zah5XgErUmFAlMZZEu0k?p=preview

我的看法是使用 Array.prototype.concat(( 进行 zip 和映射:

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));

只是不使用Observable.of将数组作为参数并重新发出其所有值的Observable.from

var s1 = Observable.from([1, 2, 3]);
var s2 = Observable.from([4, 5, 6]);
s1.merge(s2).subscribe(val => {
   console.log(val);
});

也许您可能更喜欢concat而不是merge,但在这种情况下,使用纯数组,它会给出相同的结果。

这将为您提供:

1
2
3
4
5
6

如果您希望将其作为单个数组,您也可以附加toArray()运算符。顺便说一句,你可以用Observable.of实现同样的效果,但你必须用Observable.of.call(...)来调用它,这可能是不必要的复杂,而且使用起来更容易Observable.from()

也许你可以用List而不是Array来做到这一点:

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

然后

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

@maxime1992接受的答案现在将导致当前版本的 RXJS 出现弃用警告。这是一个更新的版本:

import { forkJoin, of } from 'rxjs';
import { map } from 'rxjs/operators';
const s1$ = of([1, 2, 3]);
const s2$ = of([4, 5, 6]);
Observable
  .forkJoin([s1$, s2$])
  .pipe(     
    .map(([s1, s2]) => [...s1, ...s2])
  )
.do(console.log)
.subscribe();

最新更新