2

In rxjs I want to make a condition over multiple flatmap so I don't execute the second and third flatmap and I go directly to the subscribe :

this.authenticationAPI.getUser()
       .flatmap(response1 => if(response1 != null) // I want to go directly to subscribe
       .flatmap(response2 => return observable2(response2))
       .flatmap(response3 => return observable3(response3))
       .subscribe(response 4 => console.log(response4));

I thought about passing null observables to the second and third flatmap but is there any other solution?

Brahim LAMJAGUAR
  • 1,254
  • 5
  • 19
  • 28

2 Answers2

4

You should separate to 2 cases: failure and success using filter. This way is more declarative and easier to read

const response$ = this.authenticationAPI.getUser();

// failure
response$
  .filter((res) => !res)
  .subscribe(() => {
    console.log('Unauthentication')
  });

// success
response$
  .filter((res) => res)
  .flatmap(response2 => return observable2(response2))
  .flatmap(response3 => return observable3(response3))
  .subscribe(response 4 => console.log(response4));
hgiasac
  • 2,183
  • 16
  • 14
2

You'd be best served by nesting your flatmaps slightly - this example uses RxJS 5.5/6 "pipe" operators, if you're using an earlier version of RxJS you'll need to translate this slightly to map to the older syntax (comment if needed and I'll add an example):

this.authenticationAPI.getUser().pipe(
    map((response1) => {
        if (response1 != null) return of(response1);
        else return of(response1).pipe(
            flatMap((response2) => observable2(response2)),
            flatMap((response3) => observable3(response3))
        )
    })
).subscribe(response1or4 => console.log(response1or4));
Mark Hughes
  • 7,264
  • 1
  • 33
  • 37