Ashley
Ashley

Reputation: 432

RXJS - waiting until both observables are complete

I am new to RXJS and I am writing a validation function where potentially 2 modals pop up (one after the other) and the user has to confirm they are okay with breaking the validation rules.

I am calling it like this:

this.isValidAssignment(x,y,z).subscribe(result => {
    if (!result) { return; }
    ...do something...
});
isValidAssignment(x, y, z): Observable<boolean> {
      if (x === y){
          of(false)
      }
      if (x < y) {
          return this.confirmIncorrectAssignment();
      }
      if (y !== z) {
          return this.confirmIncorrectAssignment();
      }

      return of(true)
  }

// returns true if they click yes and false if they click no
confirmIncorrectAssignment(): Observable<boolean> {
    const dialogRef = this.dialog.open(ConfirmCancelModalComponent);

    return dialogRef.afterClosed();
  }

My problem is if the first confirmation executes it goes ahead and returns an Observable and it the second validation is never checked.

What is the best way in RXJS to make sure the user confirms both modals? I only want it to emit true if both observables have completed and they clicked yes on both.

Upvotes: 1

Views: 188

Answers (1)

Ashley
Ashley

Reputation: 432

I managed to find a solution using the RXJS forkJoin and map operators. My updated code looks like this.

isValidAssignment(x, y, z): Observable<boolean> {
    let o1: Observable<boolean> = of(true);
    let o2: Observable<boolean> = of(true);
      if (x === y){
          return of(false)
      }
      if (x < y) {
          o1 = this.confirmIncorrectAssignment();
      }
      if (y !== z) {
          o2 = this.confirmIncorrectAssignment();
      }

      return forkJoin([o1, o2]).pipe(map((x) => x[0] && x[1]));
  }

because I intialize the observable to true, it will emit true if not otherwise assigned to the return of the modal. Assuming both validations are triggered, once they both complete the forkJoin will pipe it into the map which will then use boolean logic to return true or false.

Upvotes: 2

Related Questions