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.
There are several options:
Use take(1)
with forkJoin()
to complete each source Observable:
forkJoin(o1$.take(1), o2$.take(1))
Use zip()
and take(1)
to emit only when all source Observables have emitted the same number of items:
zip(o1$, o2$).take(1)
Use combineLatest()
to emit when any of the source Observables emit:
combineLatest(o1$, o2$)
Jan 2019: Updated for RxJS 6
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.