Search code examples
angularrxjsobservablereactive-programming

RXJS: pipe observable on condition


I have post request to create team on my website and put request to upload avatar for my team.

In team creation form there is field for avatar upload.

After user submits a form, create request is being sent and here I need to pipe avatar upload request to it and use what server returned me from first (team creation) request. BUT ONLY if avatar is not null (if user uploaded it).

So i want something like this (this.team is TeamService):

    this.team.createTeam(teamRequest)
    .pipe(
        flatMap(next => this.team.uploadAvatar(next.uuid, avatar)), // if avatar !== null
        catchError(() => {
            this.onError();
            return EMPTY;
        })
    ).subscribe(next => {
        enter code here...
    });

Solution

  • Simply use filter operator as demonstrated below:

    this.team.createTeam(teamRequest)
      .pipe(
        filter(() => avatar),
        flatMap(next => this.team.uploadAvatar(next.uuid, avatar)),
        catchError(() => {
          this.onError();
          return EMPTY;
        })
      )
      .subscribe(next => {
        enter code here...
    });