A forkJoin alternative for uncompleted observables

2020-03-01 09:15发布

问题:

constructor(
    private route: ActivatedRoute,
    private http: Http
){
    // Observe parameter changes
    let paramObs = route.paramMap;

    // Fetch data once
    let dataObs = http.get('...');

    // Subscribe to both observables,
    // use both resolved values at the same level
}

Is there something similar to forkJoin that triggers whenever a parameter change is emitted? forkJoin only works when all observables have completed.

I just need to avoid callback hell, any alternative that complies is welcome.

回答1:

There are several options:

  1. Use take(1) with forkJoin() to complete each source Observable:

    forkJoin(o1$.take(1), o2$.take(1))
    
  2. Use zip() and take(1) to emit only when all source Observables have emitted the same number of items:

    zip(o1$, o2$).take(1)
    
  3. Use combineLatest() to emit when any of the source Observables emit:

    combineLatest(o1$, o2$)
    

Jan 2019: Updated for RxJS 6



回答2:

In addition to the other answer, consider using Observable.concat() which will handle each observable in sequence. Here's an example:

const getPostOne$ = Rx.Observable.timer(3000).mapTo({id: 1});
const getPostTwo$ = Rx.Observable.timer(1000).mapTo({id: 2});

Rx.Observable.concat(getPostOne$, getPostTwo$).subscribe(res => console.log(res));

A good article outlining 6 operators you should know.