首页 > 解决方案 > Condition the execution of a flatmap in rxjs - angular 5

问题描述

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?

标签: angularrxjsflatmap

解决方案


您应该分为 2 种情况:使用filter. 这种方式更具声明性,更易于阅读

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

推荐阅读