CombineLatest替代方案,用于合并或合并Observable

时间:2018-07-02 15:21:24

标签: merge rxjs observable

起初我觉得combineLast很合适,但是当我阅读文档时似乎并不是这样:“请注意,combineLatest直到每个forkJoin都不会发出初始值可观察到的至少发出一个值。”……当然,我碰到了那个异常。我尝试了mergesomeObs的各种组合,但我做对了。

用例非常简单,方法0返回SomeObs或更多可观察对象,并在其上循环。基于OtherObs[]对象上的值,我将一个新构造的可观察值Array推到Observable<OtherObs[]>的{​​{1}}中。该数组“需要”合并为一个可观察的对象,在返回它之前,我要进行一些转换。

具体来说,我很难用适当的内容替换combineLast运算符...

public obs(start: string, end: string): Observable<Array<OtherObs>> {
  return this.someObs().pipe(
    mergeMap((someObs: SomeObs[]) => {
      let othObs: Array<Observable<OtherObs[]>> = [];

      someObs.forEach((sobs: SomeObs) => {
        othObs.push(this.yetAnotherObs(sobs));
      });

      return combineLatest<Event[]>(othObs).pipe(
        map(arr => arr.reduce((acc, cur) => acc.concat(cur)))
      );
    })
  );
}

private yetAnotherObs(): Observable<OtherObs[]> {
  /// ...
}

private somObs(): Observable<SomeObs[]> {
  /// ...
}

1 个答案:

答案 0 :(得分:3)

combineLatest的“问题”是(如您所说的)“将不会发出初始值,除非每个可观察对象发出至少一个值”。但这不是问题,因为您可以使用RxJS运算符startWith

因此,您的可观察对象将获得初始值,并且combineLatest的工作方式像一个迷惑符;)

import { of, combineLatest } from 'rxjs';
import { delay, map, startWith } from 'rxjs/operators';

// Delay to show that this observable needs some time
const delayedObservable$ = of([10, 9, 8]).pipe(delay(5000));

// First Observable
const observable1$ = of([1, 2, 3]);

// Second observable that starts with empty array if no data
const observable2$ = delayedObservable$.pipe(startWith([]));

// Combine observable1$ and observable2$
combineLatest(observable1$, observable2$)
  .pipe(
    map(([one, two]) => {
      // Because we start with an empty array, we already get data from the beginning
      // After 5 seconds we also get data from observable2$
      console.log('observable1$', one);
      console.log('observable2$', two);

      // Concat only to show that we map boths arrays to one array
      return one.concat(two);
    })
  )
  .subscribe(data => {
    // After 0 seconds: [ 1, 2, 3 ]
    // After 5 seconds: [ 1, 2, 3, 10, 9, 8 ]
    console.log(data);
  });

See example on Stackblitz