A forkJoin alternative for uncompleted observables?

Viewed 16055
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.

3 Answers

A small trick to avoid breaking of observable subscriptions if any one of the observable fails.


import { throwError, of, forkJoin } from "rxjs";
import { catchError, take } from "rxjs/operators";

//emits an error with specified value on subscription
const observables$ = [];
const observableThatWillComplete$ = of(1, 2, 3, 4, 5).pipe(take(1));

const observableThatWillFail$ = throwError(
  "This is an error hence breaking the stream"
).pipe(catchError((error) => of(`Error Catched: ${error}`)));

observables$.push(observableThatWillComplete$, observableThatWillFail$);

forkJoin(observables$).subscribe(responses => {
  console.log("Subscribed");
  console.log(responses);
});

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.

Related