How to connect two observable and return true if they completes in Angular using RxJs?

Viewed 120

I'm creating a guard and I'm using canActivate. I'm also using NgRx state management.

Scenario:

If materialState$ has data, return true
If userCurrency$ has data, return true

I would like to connect them into one observable and if their both have data return true

My code:

export class IsTrue implements CanActivate {
   constructor(private userFacade: UserFacade) {}
    
   canActivate(): Observable<boolean | UrlTree> | boolean | UrlTree {
      this.userFacade.getUserStatiscis();
    
      const materialState$ = this.userFacade.materialState$.pipe(
          filter((data) => data !== null),
          map((data) => {
             if (data) return true;
          }),
      );
    
      const userCurrency$ = this.userFacade.selectUserCurrency$.pipe(
          filter((data) => data !== null),
          map((data) => {
             if (data) return true;
          }),
      );
    
// return forkJoin(materialState$, userCurrency$);
    }
}

I've tried using forkJoin, merge, and concat but without success.

@Edit

I found a working "solution", could you rate that?

      return combineLatest([materialState$, userCurrency$]).pipe(
            map((data) => {
                if (data) return true;
            }),
        );
3 Answers

You can achieve that using combineLatest operator, then mapping the result to a boolean, like the following:

combineLatest([
  this.userFacade.materialState$.pipe(filter(data => !!data)),
  this.userFacade.selectUserCurrency$.pipe(filter(data => !!data))
]).pipe(
  map(([materialState, userCurrency]) => !!materialState && !!userCurrency)
);

If all you want to know is whether they both emitted at least one value combineLatest is your friend, because it only starts to emit after all sources emitted at least once.

combineLatest([
  this.userFacade.materialState$,
  this.userFacade.selectUserCurrency$
]);

if you explicitely need the true/false you can append

.pipe(
  map(() => true)
);
const materialState$ = this.userFacade.materialState$.pipe(
    filter(data => !!data)
);

const userCurrency$ = this.userFacade.selectUserCurrency$.pipe(
    filter((data) => !!data)
);


const connectedStream$ =  combineLatest([ materialState$, userCurrency$ ]);
Related