Reputation: 469
I've got a piece of following code:
.flatMap(sth -> {
obj = sth.getSomeLast();
if (obj.someField == null) {
return dao.loadInfo(obj.id).map(info -> Entry(1, 2, info));
} else {
return Single.just(Entry(1, 2, null));
}
})
.doOnNext(entry -> writer(entry));
How can I avoid using 2 returns (inside of if/else)? I was thinking about .filter
and then defaultIfEmpty()
Upvotes: 0
Views: 2226
Reputation: 109
you can use filter and defaultIfEmpty
Observable.just("one", "two")
.filter(s -> !s.equals("a"))
.map(s -> s + "!")
.defaultIfEmpty(load());
But I don't recommend you to call any method in defaultIfMethod() because method load() will be called not depending on result of filter()
That's why you can use
.switchIfEmpty(Observable.fromCallable(() -> load()))
swithIfEmpty will work like lazy style, but defaultIfEmpty has in parameters some objects and so It'll work like eager style
Upvotes: 3