0

I have a kind of chain of validators that I need to run on my app:

public class Validator1 : IValidator
{
    public IObservable<ValidatorResult> Validate()
    {
        ....
    }
}
...
public class Validator2 : IValidator // this validator will return a fail
...
public class Validator3 : IValidator
...

Now I need to run them in sequence until one fails(ValidatorResult.Status == Status.Fail). A Where was my first thought, but of course, it's not a good solution for this because it will kill the whole chain.

So I tried something like

Validator1.Validate(address)
    .Concat(Validator2.Validate(address)).Where(x => x.Status == ValidatorStatus.Successful)
    .Concat(Validator3.Validate(address))

But that results in the Validator2 not been included in the final chain, and the Validator3 end up being called anyway.

So, what I wanted here is that the signal from Validator1 and Validator2 would hit my Subscribe(), but nothing after that.

Giusepe
  • 655
  • 5
  • 15
  • Does `Validate` return an observable of one value? Or possibly multiple? This is a very weird setup, since your validators don't accept an `IObservable`. I assume you're passing something via constructor. With Rx you generally look to pipeline Observables, you're trying to pipeline these custom validators based on output from observables. – Shlomo Feb 08 '18 at 15:07
  • Yes, it does return only one value, and I could change it to accept an IObservable as parameter, but I don’t see how that would help. – Giusepe Feb 08 '18 at 17:10

1 Answers1

1

This would do the job:

var chain = new IValidator[]
{
    new Validator1(),
    new Validator2(),
    new Validator3()
};

chain
    .Select(v => v.Validate())
    .Concat()
    .TakeWhile(vr => vr.Status == ValidatorStatus.Successful)
    .Subscribe(
        vr => Console.WriteLine(vr.Status),
        () => Console.WriteLine("Done"));
Aaron
  • 622
  • 7
  • 15
  • 1
    I had to make one small change and use a "TakeWhileInclusive" https://stackoverflow.com/questions/14697658/rx-observable-takewhile-checks-condition-before-each-element-but-i-need-to-perfo – Giusepe Feb 09 '18 at 15:42