Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created December 13, 2018 16:49
Show Gist options
  • Save hollygood/ad44e16f0cb28bb4ef60fb13dd115ab8 to your computer and use it in GitHub Desktop.
Save hollygood/ad44e16f0cb28bb4ef60fb13dd115ab8 to your computer and use it in GitHub Desktop.
Mutiple Http streams with RxJS
/**
* @function forkJoin multiple requests with ngrx selects
* we can't use forkJoin for ngrx selects because this method requires the Observables being 'complete'
* in case of ngrx store, all of their observables are usually based on a BehaviorSubject, and will never complete
* the only way we can do is using like this: forkJoin(user$.take(1), customCarList$.take(1)
*/
const result$ = forkJoin([
this.store.select(selectOne).pipe(take(1)),
this.store.select(selectTwo).pipe(take(1)),
this.store.select(selectThree).pipe(take(1))
]);
result$.subscribe();
/**
* using combineLatest() with ngrx selects
*/
combineLatest(
this.store.select(selectOne),
this.store.select(selectTwo),
this.store.select(selectThree)
)
.pipe(
tap(([one, two, trhee]) => {
// do something here
})
)
.subscribe();
/**
* switchMap() for requests that have to happen in a specific order.
*/
this.userService.getUserId()
.switchMap(userResult =>
this.userService.getUserPermission(userResult.id)
.switchMap(permissionsResult =>
this.userService.getUserInfo(userResult.id)
.map(infoResult => ({
id: userResult.id,
name: userResult.name,
permissions: permissionsResult.permissions,
info: infoResult.info
}))
)
)
.subscribe(v => console.log('switchmap:', v));
/**
* flatMap() combining Observables in series and parallel
*/
getBooksWithAuthor(): Observable<any[]> {
return this.http.get('/api/books/')
.map((res: any) => res.json())
.flatMap((books: any[]) => {
if (books.length > 0) {
return Observable.forkJoin(
books.map((book: any) => {
return this.http.get('/api/authors/' + book.author_id)
.map((res: any) => {
let author: any = res.json();
book.author = author;
return book;
});
});
);
}
return Observable.of([]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment