使用RxJava过滤项目列表

时间:2017-12-17 17:21:27

标签: rx-java

如何使用RxJava过滤项目列表?

我有以下代码,loadData()会发出List<Chatroom>

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

我希望在loadData()之后应用过滤器。您可以在下一个代码段中看到我的解决方案,但也许有更好的方法吗?

 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)));

2 个答案:

答案 0 :(得分:4)

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

这应该有所帮助。

答案 1 :(得分:2)

你的解决方案很好,如果没有&#34;功能正常&#34;风格。

通常,我会写一些像 -

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