RXJS-将两个流结果合并到一个排序的数组中

时间:2019-08-06 06:48:59

标签: javascript arrays rxjs

我有两个流。可以说:

const firstStream = Rx.of([
  {
    first: 'first',
  }, {
    third: 'third',

  }
]);

const secondStream = Rx.of([
  {
    second: 'second'
  }, {
    fourth: 'fourth'
  }
]);

现在我想要一个结合了这两个流的结果并映射如下结果数组的流:

const resultArr = [
  {
    first: 'first',
  }, 
  {
    second: 'second'
  },
  {
    third: 'third',
  },
  {
    fourth: 'fourth'
  }
];

我尝试将CombineLatest与rxjs flatmap运算符一起使用,但是没有解决。我提供了一个Stackblitz游乐场来测试:StackBlitz

我可以肯定有很多方法可以做到这一点。也许有人可以帮助我:)

2 个答案:

答案 0 :(得分:3)

const { from, merge } = rxjs;
const { reduce, map, mergeMap } = rxjs.operators

const a = from(['first', 'third']);
const b = from(['second', 'fourth']);


const sortMap = {
  first: 0,
  second: 1,
  third: 2,
  fourth: 4,
}

merge(a, b).pipe(
  // wait until every observable has completed,
  // zip all the values into an array
  reduce((res, item) => res.concat(item), []),
  
  // sort the array accordingly to your needs
  map(list => list.sort((a, b) => sortMap[a] - sortMap[b])),
  
  // flatten the array into a sequence
  mergeMap(list => list),
).subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js" integrity="sha256-mNXCdYv896VtdKYTBWgurbyH+p9uDUgWE4sYjRnB5dM=" crossorigin="anonymous"></script>

答案 1 :(得分:0)

在此处输入代码正如您所说的,流首先完成,然后,您需要将排序后的值作为流的单个输出,因此我建议使用forkJoin运算符,该运算符将Wait for Observables to complete and then combine last values they emitted.

const { of, forkJoin } = rxjs;
const { map } = rxjs.operators;

let a$ = of([1, 8, 10, 4]);
let b$ = of([3, 5, 43, 0]);

forkJoin(a$, b$)
  .pipe(
    map(([a, b]) => [...a, ...b]),
    map(x => x.sort((a, b) => a - b))
  )
  .subscribe(x => {
    console.log('Sorted =>', x);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js" integrity="sha256-mNXCdYv896VtdKYTBWgurbyH+p9uDUgWE4sYjRnB5dM=" crossorigin="anonymous"></script>