I want an observable to be delayed depending on its value. For example:
of(someBool).pipe(delay(1000))
skip delay when someBool
is false, but wait a sec when it's true.
You can use delayWhen
for that:
of(someBool).pipe(
delayWhen(val => val ? interval(1000) : of(undefined))
)
Side note, according to the docs using empty()
instead of of()
should IMHO work, but doesn't appear to. I believe this might be a bug. I have reported it.
Example. Suppose you are implementing a login page and you want to wait until you get some token to put it in another Observable or Cookies. Then you can wait a value of your Observable (someBool
here I used this.authService.isLoggedIn
). So you can do something like this:
return this.authService.isLoggedIn
.pipe(
delayWhen(loggedIn => loggedIn ? interval(0) : interval(10000)),
);
And when a state of isLoggedIn
is changed a user will be logged in.
Note: In future versions, empty notifiers will no longer re-emit the source value on the output observable.
someBool$.pipe(
delayWhen(val => val ? timer(1000) : timer(0))
)