OmerKarakose OmerKarakose - 1 month ago 42
Android Question

android rxjava sort list with comparator class

I started to use rxjava with my android projects. I need to sort returning event list from api call. I wrote comparator class to sort list :

public class EventParticipantComparator {

public static class StatusComparator implements Comparator<EventParticipant> {

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


I can use this class with classic Collections class.

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


how can I achieve this situation with reactive way ? also if there are any way to sort list asynchronously, I will prefer that way.

Reactive way without sorting list :

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

}
});

Answer

If I had not read the Javadoc for Collections.sort(), I would have recommended something like map(list -> Collections.sort (list, comparator)) to convert it into a sorted array; here, map is the observable mapper.

However, the sort method above is an in-place sorting algorithm, which affect the underlying array rather than returning the fully sorted array. So instead you should do something like this:

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

This will sort each incoming List<EventParticipant> individually and asynchronously.