Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava filtering empty list and using firstOrDefault

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.

like image 771
breakline Avatar asked Sep 08 '17 11:09

breakline


1 Answers

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.

like image 88
Kiskae Avatar answered Oct 20 '22 15:10

Kiskae