RxJava filter 'else'

I want to share my observable if/else example

Sort of:

 A[] array = new A[10]; for (int i = 0; i < array.length; i++) { array[i] = new A(getRandomString(), getRandomInt()); } Observable.from(array) .filter(a -> condition(a)) .// <--- do stuff if condition returns true .// <- back to parent .filter(a -> complexCondition(a)) // filter all elements(!) .// <--- do stuff if complex condition returns true .// <- back to iterate all elements 

Is it possible?

+6
source share
3 answers

The Observable does not work this way, you should think that the observable is like a stream in which you can get some elements, others. Closest if / else, which you find in observables, will be using GroupsBy.

Here you have an example of practicality, which I explained how it works

https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/transforming/ObservableGroupBy.java

+3
source

One way to achieve this behavior is to subscribe to your data twice and filter it differently:

 Subscription subscriptionA = Observable.from(array) .filter(a -> condition(a)) .subscribe(...) // <-- do stuff for condition A Subscription subscriptionB = Observable.from(array) .filter(a -> complexCondition(a)) .subscribe(...) // <-- do stuff for condition B 
+2
source

To expand Ken’s answer , another option is to β€œfork” the Observed into two branches using the play operator . This ensures that the original observable is called only once. This is useful if there are some expensive treatments or side effects in the chain:

 ConnectableObservable<A> connectable = Observable.fromArray() .replay(); connectable .filter(a -> condition(a)) .// <--- do stuff if condition returns true connectable.connect(); // do this after the first branch connectable .filter(a -> complexCondition(a)) // filter all elements(!) .// <--- do stuff if complex condition returns true connectable .// <- iterate all elements 

Remember that all branches must handle both onNext and onError events.

0
source

All Articles