Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Break Chain on Conditional

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!

like image 742
Rich Luick Avatar asked May 05 '16 13:05

Rich Luick


1 Answers

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
like image 92
Balázs Édes Avatar answered Oct 22 '22 09:10

Balázs Édes