11

I am creating an observable sequence and I am basically looking for a nice way to break the chain if a condition is not met. Ideally we could through an error in this scenario. This is basically to remove an if/else statement in a flatmap operator. This is something like I have now

flatMap(new Func1<User, Observable<Response>>() {
                    @Override
                    public Observable<Response> call(Result result) {
                        if(isValid(result))) {
                            return api.getObservableResponse(); //some retrofit observable
                        } else {
                            observer.onError();
                            return null; //??? I guess this would force an error
                        }
                    }
                })

I've seen operators such as filter() and all the other conditional ones but I am not sure if any of them meet my requirements. Is there a better way to do this? Or is what I have looking fine? Thanks!

Rich Luick
  • 2,354
  • 22
  • 35
  • `return Observable.error(exception)` ? – Than May 05 '16 at 14:18
  • 1
    @Than I guess that would force an error. Im more looking for some sort of method I can chain in to remove the if/else entirely, if that exists. – Rich Luick May 05 '16 at 14:21
  • 1
    Why not filter on your condition before applying flatMap? – JohnWowUs May 05 '16 at 14:54
  • @JohnWowUs I could although I fell like that would add more code than I currently have. It would be ideal to throw an error if this happens automatically. If I understand correctly. Filter will just stop the flow if it is false? Or will it stop an go to onError? – Rich Luick May 05 '16 at 16:14
  • 1
    How about `return Observable.empty()` ? – mewa May 05 '16 at 16:21
  • @RichLuick It would simply not emit anything. You should not be using onError for "normal" flow control. It should only be used for unrecoverable errors. It completely kills you observable i.e. you're not going to emit any more items after emitting an error. You can return an error in your current flatMap using Observable.error(new Exception("Invalid Response")). – JohnWowUs May 05 '16 at 16:44
  • @JohnWowUs Thanks, just figured I would check if there is a function that would do that for me. Basically, if that else scenario happens, we simply want to exit the flow and treat it like an error. I will use the Observable.error method in this case – Rich Luick May 05 '16 at 17:04

1 Answers1

3

How about using takeWhile - docs?

Observable<T> whatever = ...

Observable<T> untilConditionMet = whatever
   .takeWhile(this::isValid) // modify according wherever isValid comes from
   .flatMap(r -> api.getObservableResponse()); // only doing this until isValid
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89