RxJS – How to wait until all observables emit (combineLatest)


,

In RxJS, you often need to work with values from multiple observables simultaneously. A common scenario is waiting for several data streams to complete before you can perform an action.

The combineLatest operator is the perfect for this. It combines multiple observables and emits an array containing the latest value from each one.

combineLatest

  1. It waits until every source observable has emitted at least one value.
  2. Once all sources have emitted, it will emit a single array with the latest value from each observable.
  3. After that initial emission, it will emit a new array anytime any of the source observables emits a new value.

Here is an example.

      combineLatest([
        userProfile$,
        userPermissions$
      ]).pipe(
        // Ensure we don't proceed if either value is null or undefined
        filter(([profile, permissions]) => !!profile && !!permissions), 

        // Only emit when the combined values have actually changed
        distinctUntilChanged(([prevProfile, prevPermissions], [currentProfile, currentPermissions]) =>
          prevProfile.id === currentProfile.id && prevPermissions.canEdit === currentPermissions.canEdit
        )
      ).subscribe(([profile, permissions]) => {
        console.log('Both profile and permissions have been received.');
        console.log (profile, permissions);

        // Now you can safely work with both values
      }),

In this example:

combineLatest: Subscribes to both userProfile$ and userPermissions$.

filter(...): Acts as a safeguard to ensure neither result is null or undefined.

distinctUntilChanged(...): Prevents the code from re-running if an observable emits a value that is identical to its previous one.

Reference

For more information, Check the link below about combineLatest.

https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest

Leave a Reply

Your email address will not be published. Required fields are marked *