作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我开始在我的 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/
我刚开始使用 Dagger 2,想知道与我目前用来实现依赖注入(inject)的技术相比,它有什么优势。 目前,为了实现 DI,我创建了一个具有两种风格的项目:mock 和 prod。在这些风格中,我
我是一名优秀的程序员,十分优秀!