Conditional object creation within a stream in RxAndroid

263 views Asked by At

I am still new to RxAndroid and I want to load a single object within a stream. This object can be loaded as an Observable from two different classes. In my szenario at first the object is loaded from provider1, if however null is provided, the object will be loaded from provider2.

My problem is that

  • I have no idea how to elegantly check for null
  • I have no idea how to deal with both, Observable<MyObj> and MyObj in the same method

At the moment my code looks like this

return provider1.getObject()
                .flatMap(o -> {
                    if(o == null) return provider2.getObject();
                    else return Observable.just(o);
                });

This doesn't really look nice, is there maybe an operator that I am missing? Or is there at least a method to flatten a single Observable so that I could do something like:

return provider1.getObject()
                .map(o -> {
                    if(o == null) return provider2.getObject().flatten();
                    else return o;
                });

Or am I just doing it totally the wrong way? Any help appreciated.

1

There are 1 answers

0
zsxwing On BEST ANSWER

You can use switchIfEmpty, such as

return provider1.getObject()
           .filter(o -> o != null)
           .switchIfEmpty(provider2.getObject());

BTW, switchIfEmpty is added since RxJava 1.0.5. You may need to specify the RxJava version in your build script.