如何连接多个数组可观察对象,使某些对象可能不会发出任何流

问题描述

假设我有以下情况:

allItems$: <(TypeA | TypeB)[]>;
arr1$: TypeA[]; // [{a: 1,b: 2},{a: 3,b: 4}]
arr2$: TypeA[];
arr3$: TypeB[]; // [{ b:1,c: 2},{ b:3,c: 4}]
arr4$: TypeB[];

我想将所有内容合并为一个数组,但是其中一些流可能不会发出任何值,您知道哪个是合适的运算符吗?

this.allItems$ = operator([
  arr1$,arr2$,arr3$,arr4$
]).pipe(
   // returned value
);

所需的输出

// [{a: 1,b: 4},{ b:1,c: 4}]

解决方法

您要查找的是 ZIP ,但是如果您的可观察对象之一未发出值,它将无法正常工作,因此我建议您使用 MERGE 并尝试在每次拥有发射值时将其推入数组,这是适合您情况的可行解决方案:

import { delay,last,switchMap,tap } from "rxjs/operators";
import { of,zip,merge } from "rxjs";


let array = [];

const sourceOne = of("Hello");
const sourceTwo = of("World!");
const sourceThree = of(); // observable that doesn't emit a value
const sourceFour = of("World!");

const example = merge(
 sourceOne,sourceTwo.pipe(delay(1000)),sourceThree.pipe(delay(2000)),sourceFour.pipe(delay(3000))
);

const data = example.pipe(
       tap((val) => array.push(val)),switchMap(() => of(array))
       );
const subscribe = data.pipe(last()).subscribe(val => console.log(val));
//output: ["Hello","World!","World!"]

这是有效的解决方案https://stackblitz.com/edit/typescript-u4swov?file=index.ts