Reputation: 47
I'm trying to get the first item from a list using RxJava. However, I don't want it to throw an error if the item doesn't exist. Instead I want to be able to handle that myself by providing a default item.
The code I created below works correctly in retrieving the first item in a list. Though I can't figure out how to incorporate .exists()
into it.
api.getLibraryEntries(username)
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<List<Entry>, Observable<Entry>>() {
@Override
public Observable<Entry> call(List<Entry> Entries) {
return Observable.from(Entries);
}
})
.first(new Func1<Entry, Boolean>() {
@Override
public Boolean call(Entry entry) {
return entry.getId() == id;
}
})
.subscribe(
new Action1<Entry>() {
@Override
public void call(Entry entry) {
view.showEntry(entry);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
view.showError(throwable.getMessage());
}
});
Any help is appreciated.
Upvotes: 4
Views: 2511
Reputation: 15054
There is a firstOrDefault
operator:
// ...
.firstOrDefault(yourDefaultValue, new Func1<Entry, Boolean>() {
@Override
public Boolean call(Entry entry) {
return entry.getId() == id;
}
})
// ...
Upvotes: 4