Filter list of objects in RxJava

user2908751 picture user2908751 · Feb 8, 2018 · Viewed 13.6k times · Source

I am trying to filter the list on the basis of it's property. For example, Sensors class has a property isActive and I want to get all the objects with isActive as true but I am unable to do it. I tried different ways but I didn't find the solution. Can someone help me to do it?

Here is my code:

mCompositeDisposable.add(
    fcService.getStationList()
    .subscribeOn(Schedulers.io())
    .flatMap(stations -> {
        return fcService.getSensorList(stations.get(0).getName().getOriginal());}
    ).subscribe(this::handleSensors, this::handleError));

Answer

azizbekian picture azizbekian · Feb 8, 2018

First, you need to emit each item from the List individually. That can be achieved using flatMap() and Observable.fromIterable(Iterable).

Then apply filter() operator. Lastly, collect all of those items into list again using toList().


    service.getSensorsList()
              .flatMap(Observable::fromIterable)
              .filter(sensor -> sensor.isActive())
              .toList()
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(this::handleSensors, this::handleError)