Home > other >  Correct way of returning angular observable boolean?
Correct way of returning angular observable boolean?

Time:07-19

I am facing problems returning observable boolean value in the following method.

  isPresent$(): Observable<boolean> {
    let obsA = this.isMsgAPresent$() // return list of Message objects
      .pipe(map(msgs => msgs != null && msgs.length > 0))
    let obsB = this.isMsgBPresent$() // return list of Message objects
      .pipe(map(b => b?.msgs.some(m => this.isTriggered(m))))
    return obsA || obsB
  }

this was working before in angular 12 but after updating to the latest depedencies it started evaluating to null. So I am wondering what is the possible reason that it was working before and not now? Any Idea what changed and a possible alternate soultion would help me debug my problem.

CodePudding user response:

You can use forkJoin to construct a new observable and map all boolean values into a single boolean value.

import {forkJoin, map} from "rxjs";

...

isPresent$(): Observable<boolean> {
    return forkJoin([this.isMsgAPresent$(), this.isMsgBPresent$()]).pipe(
        map(([first, second]) => first || second)
    )
}

You may have a look at this Stackblitz where this code runs within your browser.

CodePudding user response:

Using the forkJoin as was mentioned in the other answer might not be sufficient if you want to test every value emitted by the two observables. forkJoin will emit only the last values from both observables.

i.e. if you have something like forkJoin([of(1, 2), of(3, 4)]) the result will be [2, 4].

If you want to test every value you can use concatMap or even mergeMap because you don't care about the order of emissions.

  • Related