Home > Software engineering >  Use rxjs operators to wait until both requests complete at once
Use rxjs operators to wait until both requests complete at once

Time:11-06

  public reloadUser(){
    this.reloadUserGating();
    return this.request.get(`${this.url}/`).pipe(tap(user => this.currentUserSubject.next(user)));
}

I need to make reloadUser() method wait until both requests complete and then emit the observable. But it should not be sequally - both at once.

CodePudding user response:

If reloadUserGating returns an observable then you can use forkJoin

Some good examples of forkJoin with Angular HttpClient here:

CodePudding user response:

To give you the syntax and return type of forkjoin in this context:

public reloadUser(): Observable<[ReturnType1, ReturnType2]>{
    const obs1: Observable<ReturnType1> = this.reloadUserGating();
    const obs2: Observable<ReturnType2> = this.request
      .get(`${this.url}/`)
      .pipe(tap((user) => this.currentUserSubject.next(user)));
    return forkJoin([obs1, obs2]);
}

forkJoin returns a new observable, where the result is an array containing the results of the other observables.

Note: forkJoin does require the Observables to complete, not just fire a value. combineLatest can be used if the observables don't complete.

  • Related