Search code examples
angularngrx

Get latest value of an Observable and a Behaviour Subject


I have a observable and a behaviour subject. I want to get their latest values, check if they are both true and assign the result to an observable.

  1. Observable will select a boolean from the NgRx Store:

    this.i18nStateService.defaultMarketChangeTriggered()
    
  2. BehaviourSubject is also a boolean

    this.cookieService.isCookieLayerConfirmed$
    

This is my approach.

   this.result$ = this.i18nStateService.defaultMarketChangeTriggered()
              .pipe(
                map(defaultMarketChangedTriggered => defaultMarketChangedTriggered  && !this.cookieService.isCookieLayerConfirmed$)
              );

Solution

  • I think you need a combination approach. Try using combineLatest.

    import { combineLatest } from 'rxjs';
    
    this.result$ = combineLatest(this.i18nStateService.defaultMarketChangeTriggered(),
                                 this.cookieService.isCookieLayerConfirmed$).pipe(
    
                // pluck the combination of those two observables individually to these variables
           map(([defaultMarketChangeTriggered, isCookieLayerConfirmed]) => defaultMarketChangeTriggered && isCookieLayerConfirmed), 
    );