javascriptangularrxjsrxjs6

RXJS how to use OR condition


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

Solution

  • 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