gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:52:14 24 4
gpt4 key购买 nike

我开始在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com