24 Jul 2024
2 min

delayWhen – RxJS Reference

delayWhen

delayWhen delays each emitted value from the source observable by a time span determined by another observable referred to as duration observable. When the source observable emits a value, the operator executes the callback with the value as an argument and expects the function to return a duration observable. delayWhen keeps the value emitted from the source observable in a cache until the delay observable emits a value. When that happens, it sends the delayed value to the observer.

It’s important to note that delayWhen executes the callback function to get a duration observable on every new value that comes from the source observable. It means that it keeps a registry of all duration observables for all values emitted from the source observable. Once a duration observable emits a value and the corresponding value from the source observable is sent to the observer the operator unsubscribes from this duration observable.

Optionally, delayWhen takes a second argument known as subscriptionDelay, which is an observable that can be used to delay the subscription the source observable. When subscriptionDelay emits its first value or completes, the operator subscribes to the source and starts re-emitting values with a delay. If subscriptionDelay is not provided, delayWhen will subscribe to the source observable as soon as the output observable is subscribed to.

delayWhen operator works in the following way:

  1. Subscribe to a source observable
  2. When a new value arrives from a source observable, execute the callback function to get the duration observable corresponding to this value
  3. Add the value and the corresponding duration observable to internal cache
  4. When a duration observable emits a value, send the corresponding value to the observer, unsubscribe from this duration observable and remove it from cache
  5. Once the source observable completes, send the complete notification to the observer
  6. If the source observable throws an error, send the error notification to the observer

Usage

delayWhen can be used when you need to delay a value until some other action takes place. For example, when you login a user and return the token, you may need to perform an action on the token before returning it to the calling method.

Here’s an example that demonstrates how wait until the token is added to the local storage before sending it to the observer:

login().pipe(
   delayWhen((user) => setToLocalStorage(user))
).subscribe((user) => console.log(user));

function login() {
   return fromFetch('https://reqres.in/api/users/2').pipe(
       switchMap((response) => response.json())
   );
}

function setToLocalStorage(value) {
   return of(value).pipe(
       tap((value) => {
           localStorage.setItem('token', JSON.stringify(value));
       })
   );
}

Adding a token to the local storage is just an example. You can have any synchronous or an asynchronous action instead.

Playground

Additional resources

See also

Frequently asked questions

How do I delay each emitted value in RxJS until another observable emits?

Use the delayWhen() operator, passing a callback that receives each source value and returns a duration observable. delayWhen() caches the value and emits it only when that duration observable emits its first value, then unsubscribes from it. For example, delayWhen((user) => setToLocalStorage(user)) waits until the local storage write completes before forwarding the user downstream.

What is the difference between delay() and delayWhen() in RxJS?

delay() shifts every value by a fixed time span, while delayWhen() computes a separate delay for each value by calling a callback that returns a duration observable. With delayWhen(), the value is released whenever that observable emits, so the timing depends on an external action such as a storage write or an API response rather than a fixed number of milliseconds.

How does delayWhen() handle the subscriptionDelay argument?

The optional second argument of delayWhen() is an observable that postpones subscribing to the source. The operator subscribes to the source as soon as subscriptionDelay emits its first value or completes. If you omit it, delayWhen() subscribes to the source immediately when the output observable is subscribed to.

Does delayWhen() call the duration callback once or for every emitted value?

delayWhen() executes the callback for every new value emitted by the source observable, not once. It keeps a registry of all duration observables it has created, and each one is unsubscribed after its corresponding value is sent to the observer. Be careful with expensive or side-effecting duration observables, since each source emission triggers one.

How do I wait for an asynchronous action before passing a value along in RxJS?

Return an observable that represents the action from the delayWhen() callback, such as of(value).pipe(tap(...)) for a synchronous side effect or an HTTP request for an asynchronous one. The source value is held in an internal cache until that observable emits, so downstream subscribers receive the value only after the action has produced a notification.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.