Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

                    }
                });
like image 483
okarakose Avatar asked Oct 26 '16 16:10

okarakose


2 Answers

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 ->
            //..
        }))
like image 63
Dr.jacky Avatar answered Oct 06 '22 17:10

Dr.jacky


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

like image 42
Pär Nils Amsen Avatar answered Oct 06 '22 17:10

Pär Nils Amsen