I'm trying to filter a list which might or might not be empty (or the item is not in the list). inboxData is filled by another observable:
private BehaviorSubject<InboxResponse> inboxData = BehaviorSubject.create();
public Observable<Item> getInboxItem(String id) {
return inboxData
.flatMap(response -> Observable.from(response.getData()))
.filter(item -> item.getId().equals(id))
.firstOrDefault(null);
}
In this case if response.getData() is empty firstOrDefault never runs. But why? It clearly says that it gives you back the default value if the preceeding observable emits nothing.
firstOrDefault
emits the default if the stream completes without any items being passed through the observable. For your stream to complete the BehaviorSubject
would need to signal completion. Since there is no indication that happens it would never realize it needs to send the default.
The solution is to move the filter
and firstOrDefault
to the inside of the flatMap
so the end of the list provided by getData
ends up completing the inner stream.
Note that if you're using RxJava2 as your tags suggest, null
can never be an item in the stream, so passing it as default would cause an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With