简体   繁体   中英

How to merge an array of Observables into a single Observable of the same return type

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM