12

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.

Hikmat G.
  • 2,591
  • 1
  • 20
  • 40

3 Answers3

16

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.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
4

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.

Alex Po
  • 1,837
  • 1
  • 24
  • 28
1

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))
)
am0wa
  • 7,724
  • 3
  • 38
  • 33