带有比较器类的android rxjava排序列表

标签 android sorting collections rx-java rx-android

我开始在我的 android 项目中使用 rxjava。我需要对来自 api 调用的返回事件列表进行排序。我写了比较器类来排序列表:

public class EventParticipantComparator {

    public static class StatusComparator implements Comparator<EventParticipant> {

        @Override
        public int compare(EventParticipant participant1, EventParticipant participant2) {
            return participant1.getStatus() - participant2.getStatus();
        }
    }
}

我可以将此类与经典 Collections 类一起使用。

Collections.sort(participants, new EventParticipantComparator.StatusComparator());

我怎样才能用 react 方式实现这种情况? 另外,如果有任何方法可以异步排序列表,我会更喜欢这种方式。

没有排序列表的 react 方式:

dataManager.getEventImplementer().getParticipants(event.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<EventParticipant>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<EventParticipant> eventParticipants) {

                    }
                });

最佳答案

如果我没有阅读 Collections.sort() 的 Javadoc , 我会推荐类似 map 的东西(list -> Collections.sort (list, comparator))将其转换为排序数组;在这里,map是可观察的映射器。

然而,sort上面的方法是一种就地排序算法,它影响底层数组而不是返回完全排序的数组。所以你应该做这样的事情:

dataManager.getEventImplementer().getParticipants(event.getId())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .map(unsortedList -> {
                List<EventParticipant> sortedList = new ArrayList<>(unsortedList);
                Collections.sort(sortedList, new EventParticipantComparator.StatusComparator());
                return sortedList;
            })
            .subscribe(new Subscriber<List<EventParticipant>>() {
                // ... etc.
            });

这将对每个传入的 List<EventParticipant> 进行排序单独和异步。

关于带有比较器类的android rxjava排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267383/

相关文章:

java - 在 Android 上的 SQLite 数据库中重置 AUTOINCREMENT?

python - 了解 Python 中的闭包作用域

作为数组和字典的对象的 JavaScript 排序运行时

sorting - Underscore.js不区分大小写的排序

java - 创建集合数组

操作栏中的 Android 操作按钮没有出现?

java - 我的类(class)中可以包含哪些代码行,以便对电子邮件和密码进行验证?

Java : The Map value comparison is failing to compare with the higher values. 为什么?

javascript - 如何区分事件和非事件的 NodeList 集合?

android - 通过滚动回收器 View 折叠标题图像