Reputation: 1622
What I am trying to achieve is push a few http request observables in an array and then combine all the responses and return with a single observable.
Since all the http requests resolve with the same type 'User', I just want to wait for all of them to resolve and then I can return a single observable with all Users from getUsers() function.
I'm stuck at the return merge(observableRequests)
part as I can't get the return type right and I'm not too versed in Rxjs functions.
Here are my three related functions.
getMyUser(): Observable<User> {
return this.service.get(`${this._userPath}me`).pipe(
map((serviceUser: any) => {
return parseUser(serviceUser);
}));
}
getUsers(): Observable<User[]> {
return this.getMyUser()
.pipe(switchMap((user: User) => {
const activeProvidersIds = this._getActiveProvidersIds(user.providers);
const observableRequests = activeProvidersIds.map((id: number) => this.getUserRequest(id));
return merge(observableRequests);
}));
}
getUserRequest(facDbk: number): Observable<User[]> {
return this.service.get(`${this._providerPath}${facDbk}/users`).pipe(
map((serviceUsers: any) => {
return parseUsers(serviceUsers);
})
);
}
Any help is appreciated.
Upvotes: 2
Views: 6926
Reputation: 5801
ForkJoin will work in your use case, you can follow this code
import { Observable, of, forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';
interface user {
id : string;
name: string;
}
// mimicking api requests
const httpRequest = (num): Observable<user> =>{
return Observable.create((observer)=>{
const [id,name] = [`id-${num}`,`name-${num}`];
setTimeout(()=>{
observer.next({id,name});
observer.complete();
},num*1000);
});
}
//push array of request observables and return single observable
// you can push any number of request here
const makeRequestInParallel = ():Observable<user> =>{
const reqs:Observable<user>[] = [httpRequest(1),httpRequest(2),httpRequest(3)];
return forkJoin(...reqs);
}
makeRequestInParallel().subscribe((result)=>{
console.log(result);
});
click stablitz-link
Upvotes: 3
Reputation: 1063
I guess you are looking for forkJoin
:
When all observables complete, emit the last emitted value from each.
https://www.learnrxjs.io/operators/combination/forkjoin.html
Here is an example that may helps you:
https://stackblitz.com/edit/angular-seuqh5
Upvotes: 2