Forkjoin 与空(或没有)可观察数组

Forkjoin with empty (or not) array of observables

我正在尝试检测我的所有可观察对象何时完成。我有以下 Observables:

let observables:any[] = [];
if(valid){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}
if(confirmed){
    observables.push(new Observable((observer:any) => {
        async(()=>{
            observer.next();
            observer.complete();
        })
    }))
}

Observable.forkJoin(observables).subscribe(
    data => {
        console.log('all completed');
    },
    error => {
        console.log(error);
    }
);

当我的所有功能完成时,我需要做一些事情。当 observables 数组不为空时,Forkjoin 似乎可以工作。但是当数组为空时,它永远不会被调用。我该如何解决?

您缺少订阅中的第 3 次回调。试试这个:

Rx.Observable.forkJoin([]).subscribe(
    val => {
        console.log('next');
    },
    err => {
        console.log('err');
    },
    () => {
        console.log('complete')
    }
);

空数组上的 forkJoin 立即完成。

针对 RxJS 6 更新:

  let rep: Observable<any>[] = [];

  for (let i = 0; i < areas.length; i++) { // undetermined array length
      rep.push(this.httpService.GET('/areas/' + areas[i].name)); // example observable's being pushed to array
  }
  if (rep !== []) {
    forkJoin(rep).subscribe(({
      next: value => {
        console.log(value)
      }
    }));
  }

您缺少 complete 回调。您可以传递第三个参数或传递一个 observer 对象而不是 3 个参数以使事件检查更具可读性。

yourObservable.subscribe({
  next: value => console.log(value),
  error: error => console.log(error),
  complete: () => console.log('complete'),
});

试试这个:

import { forkJoin, Observable, of } from 'rxjs';

export function forkJoinSafe<T = any>(array: Observable<T>[]): Observable<T[]> {
    if (!array.length) {
        return of([])
    }
    return forkJoin<T>(array);
}