Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list of objects in RxJava

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));
like image 292
user2908751 Avatar asked Feb 08 '18 12:02

user2908751


People also ask

How to filter list in RxJava?

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.

What are operators in RxJava?

Implement Search Using RxJava Operators Implementing the search is a common use-case in Android Apps Development. We can implement it very easily using RxJava Operators. Here is the tutorial link. Here, we have covered the operators such as filter, debounce, distinctUntilChanged, switchMap.

Why use RxJava?

RxJava is a JVM library that uses observable sequences to perform asynchronous and event-based programming. Its primary building blocks are triple O's, which stand for Operator, Observer, and Observables. And we use them to complete asynchronous tasks in our project. It greatly simplifies multithreading in our project.


1 Answers

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)

like image 64
azizbekian Avatar answered Oct 17 '22 23:10

azizbekian