How to use “if else” in Rx Java chain?
I'm new to RX Java / RX Android I want to implement this case: choose different methods according to some conditions in rxjava
I did some searches and only found that "switchifempty" might be helpful I write the following code:
getUserFromNetwork("userId") .flatMap(new Function<User,ObservableSource<User>>() { @Override public ObservableSource<User> apply(User user) throws Exception { if(!user.isVip){ //show user info on MainThread! return Observable.empty(); }else{ return getVipUserFromNetwork("userId"); } } }).switchIfEmpty(new ObservableSource<User>() { @Override public void subscribe(Observer<? super User> observer) { //show user info in main thread //just break the chain for normal user observer.onComplete(); } }).doOnNext(new Consumer<User>() { @Override public void accept(User user) throws Exception { //show vip user info in main thread } }).subscribe();
Is there a simpler way to achieve this goal?
thank you!
Solution
Flatmap () is a good choice. You can use it to split the flow, but finally the flow is merged together (all emissions of each split observable flow go to the mainstream)
I think in your case, you can handle (respond to) user emissions in a single handler because it is very similar. Just check whether it is a VIP and display it accordingly So it should look like this:
getUserFromNetwork("userId") .flatMap(new Function<User,ObservableSource<User>>() { @Override public ObservableSource<User> apply(User user) throws Exception { if (!user.isVip) { return Observable.just(user); } else { return getVipUserFromNetwork("userId"); } } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { if (user.isVip){ //display vip user }else{ //display regular user } });
In this method, you have a stream with no "side effects" in the middle of the stream
If your processing is completely different (this is not the case), you can split the stream into two independent streams and react to each stream in different ways, which can be done by multicast getuserfromnetwork() observable and from this observable Create two different observable, one will continue, such as getvipuserfromnetwork(), the other cannot, and each can have different subscriber logic (you can read here about multicast)