Mes
Mes

Reputation: 1691

Filter list of items using RxJava

How do you filter a list of items with RxJava ?

I have the following code and loadData() emits a List<Chatroom> :

repository.loadData()
        .subscribe(chatrooms -> {
            view.showData(chatrooms);
            view.showEmptyState(chatrooms.size() == 0);
        }, throwable -> Log.i("OnError", "onLoadChatrooms ", throwable)));

and I want to apply filter after loadData(). You can see my solution on the next code snippet but maybe there's a better way ?

 repository.loadData()
        .map(chatrooms -> {

            List<Chatroom> openChatrooms = new ArrayList<>();
            for (Chatroom chatroom: chatrooms){
                if (!chatroom.getBlocked().equals(IS_BLOCKED)) {
                    openChatrooms.add(chatroom);
                }
            }
            return openChatrooms;

        })
        .subscribe(chatrooms -> {
            view.showData(chatrooms);
            view.showEmptyState(chatrooms.size() == 0);
        }, throwable -> Log.i("OnError", "onLoadChatrooms ", throwable)));

Upvotes: 0

Views: 4794

Answers (2)

Ankit Kumar
Ankit Kumar

Reputation: 3723

 loadData()
     // Opther operations if any
     .filter((chatroom -> { return !chatroom.getBlocked().equals(IS_BLOCKED);})
     .toList()
     .subscribe(getObserver()); // implement your getObserver() method for observer.

This should help.

Upvotes: 4

Maxim Volgin
Maxim Volgin

Reputation: 4077

Your solution is fine, if not "functional" in style.

Normally, I would write something like -

loadData()
        .flatMap(chatrooms -> { return Observable.from(chatrooms); })
        .filter(chatroom -> { return !chatroom.getBlocked().equals(IS_BLOCKED); })
        .toList();

Upvotes: 2

Related Questions