ArthCode
ArthCode

Reputation: 102

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...
    });

Upvotes: 0

Views: 371

Answers (2)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

You could you tenary like this

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

Upvotes: 1

Rafi Henig
Rafi Henig

Reputation: 6432

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...
});

Upvotes: 1

Related Questions