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) {
}
});
Kotlin version:
disposable.add(interactor.getItemList() //It returns Observable<ItemListResponseModel>
.compose(threadTransformer.applySchedulers())
.flatMapIterable { list -> list }
.toSortedList { p1, p2 ->
(p1?.name ?: "").compareTo(p2?.name ?: "")
}
.subscribe({ items ->
//...
}, { throwable ->
//..
}))
This solution is similar to the accepted answer, but uses Rx operators to 1) split array into objects 2) sort by the instances Comparable implementation 3) do it on a dedicated computation thread;
dataManager.getEventImplementer().getParticipants(event.getId())
.flatMap(Observable::from)
.toSortedList()
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(sortedList -> {...}, error -> {...});
Note that it's preferred to use Schedulers.io for network/disk writes, Schedulers.computation for computations like sorting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With