RXJS how to use OR condition

115 Views Asked by At

I have two Observables

For example, I am waiting HTTP POST call to come back OR WebSocket call come back so I can continue. Either call come back I need to verify the information and until certain condition met. Follow example that either one come back I can continue. But if I use filter, it will stop and wait wont proceed.

switchMap(() =>
    webSocket.access.pipe(
        filter((data) => data.access.role === "ADMIN"),
        filter((data) => data.access.status === "ACTIVE")
    )
),
switchMap(() =>
    httpService.access.pipe(filter((res) => res.access === true))
);
2

There are 2 best solutions below

0
wlf On BEST ANSWER

Use the race operator:

race(
  switchMap(() =>
    webSocket.access.pipe(
        filter((data) => data.access.role === "ADMIN"),
        filter((data) => data.access.status === "ACTIVE")
    )
  ),
  switchMap(() =>
    httpService.access.pipe(filter((res) => res.access === true))
  )
).pipe(/* do subsequent operations here */);

https://www.learnrxjs.io/learn-rxjs/operators/combination/race

0
Eliseo On

I Imagine

obsPost$:Observable<any>=...
socket$:Observable<any>=
  1. We use merge to get any of the observables. But transform each observable in an object with property "id" and "data"
  2. Then filter (get the "access" value according the value of "id")
  3. Finally return only the "data"
   myObs$=merge(obsPost$.pipe(map((res:any)=>({id:'post',data:res}))
                 socket$.pipe(map((res:any)=>({id:'socket',data:res}))).pipe(
                   filter((res:any)=>{
                      const access:any=res.id=="post"? data.data.access.role:
                                                       data.access
                      return access==true || access=='ADMIN' || access=='ACTIVE')
                   }),
                   map(res=>res.data))