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>
andMyObj
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.
You can use switchIfEmpty, such as
BTW,
switchIfEmpty
is added since RxJava 1.0.5. You may need to specify the RxJava version in your build script.