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?
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.
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.
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.
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.
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"))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With