0

I have the Base Validator method which has list of ivalidator.

import { IValidator, ValidatorModel } from "../validation/ivalidator";
import { Observable } from "rxjs/Observable";

export abstract class BaseValidator implements IValidator {

    private validators = new Array<IValidator>();

    //Validators are pushed to the base validator =>Not implemented yet

    validate(): Observable<ValidatorModel> {

        for (let i = 0; i < this.validators.length; i++) {
            //How do I loop thru all the validator and call its ASYNC method 
            //one by one and break and return when there is an error ???
        }

    }
}

Each validator method exposes the validate() method which returns an observable.

export interface IValidator {
    validate(): Observable<ValidatorModel>;
}

ValidatorModel is

export class ValidatorModel {
    readonly isSuccessful: boolean;
    errors: Array<string>;
}

My question is :

How do I loop thru all the validator and call its ASYNC method one by one and break and return when there is an error ???

1 Answer 1

1

If you want the your validations to be executed one by one, use the merge operator:

validate(): Observable<ValidatorModel> {
    let obs = this.validators.map(validator=>validator.validate());
    return Observable.merge(obs);
}

If you want your validations to be executed parallel at the same time, use the forkJoin operator:

validate(): Observable<ValidatorModel> {
    let obs = this.validators.map(validator=>validator.validate());
    return Observable.forkJoin(obs);
}

As for error handling, both merge and forkJoin will throw the error whenever they encounter them, and you can handle it at your subscribe() handler. If you are doing (pipe) more operations to the Observable<ValidatorModel>, then the error will be thrown up the final stack:

someValidator.subscribe(
            (results) => {
            },
            (error) => {
                //handle error here
            },
            () => {
                //observable completed
            })

If you choose to explicitly handle the error in your base class, then use the catch operator:

return Observable.forkJoin(obs)
    .catch(error=>{
        console.log('error encountered',error);
        //handle your errors here
        //Return an empty Observable to terminate the stream
        return Observable.empty();
    });
Sign up to request clarification or add additional context in comments.

3 Comments

so, how do I "break" when I find that one of the validator has "errored" out?
I mean I want to handle error based on the isSuccessful flag not on "throwing" exception.
Also there is compile time error Observable.merge(obs) returns Observable<Observable<ValidationModel>>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.