Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular RxJS: conditional operator (if else)

I'm trying to figure out how to implement a straightforward condional operation into an observable.

this.deactivate$
    .pipe(
        filter((canDeactivate) => !canDeactivate),
        switchMap(() => Observable.of(window.confirm("message")))
    );

What I want to get is that:

if (canDeactivate) {
    return canDeactivate;
}
else {
    return window.confirm("message");
}

The problem on first above code is that when I'm filtering emitted value, the rest of operators are not performed and stream stops to populate emitted value.

Any ideas?

like image 814
Jordi Avatar asked Jun 04 '19 15:06

Jordi


People also ask

What is IIF in RxJS?

RxJS iif() operator is a creation operator used to decide which observable will be subscribed at subscription time. In other words, we can say that the RxJS iif() operator facilitates you to subscribe to the first or second observable according to the condition.

What is concatMap in RxJS?

concatMap operator is basically a combination of two operators - concat and map. The map part lets you map a value from a source observable to an observable stream. Those streams are often referred to as inner streams.

How do I use RxJS defer?

defer allows you to create an Observable only when the Observer subscribes. It waits until an Observer subscribes to it, calls the given factory function to get an Observable -- where a factory function typically generates a new Observable -- and subscribes the Observer to this Observable.

What is pipe operator in RxJS?

Operatorslink Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.


1 Answers

You can decide which observable return inside the switchMap operator, like this:

    this.deactivate$
        .pipe(
            switchMap((canDeactivate) => {
               if (canDeactivate) {
                   return Observable.of(canDeactivate);
               }
               else {
                   return Observable.of(window.confirm("message"));
               }
            })
        );

Bonus (super shorter version):

this.deactivate$.pipe(
        switchMap((canDeactivate) => Observable.of(canDeactivate || window.confirm("message"))
    );
like image 87
Llorenç Pujol Ferriol Avatar answered Sep 21 '22 16:09

Llorenç Pujol Ferriol