示例:
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
我的做法是 zip 并使用 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));
只需使用
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);
});
也许您可能更喜欢
merge
而不是concat
,但在这种情况下使用普通数组它会给出相同的结果。
这会给你:
1
2
3
4
5
6
如果您希望将其作为单个数组,您还可以附加
toArray()
运算符。顺便说一句,您可以使用 Observable.of
实现相同的效果,但您必须使用 Observable.of.call(...)
来调用它,这可能不必要的复杂,并且仅使用 Observable.from()
更容易。
也许你可以用列表而不是数组来做到这一点:
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()).suscribe(x=>console.log(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();
对于 Angular 版本 13,您可以使用
forkJoin
,如下所示:
import { forkJoin, of, map } from 'rxjs';
const s1$ = of([1, 2, 3]);
const s2$ = of([4, 5, 6]);
forkJoin([s1$, s2$])
.pipe(
.map(([s1, s2]) => [...s1, ...s2])
)
.subscribe(console.log);