Search code examples
rx-javafiltering

How to filter list in RXJava


I'm trying to filter a single<list<item>> that I get from a method

return getList(number)
    .filter { it -> it.age }  <--- problem
    .flatMap { addMoreData(it) }
    .map(mapper)

fun getList(number: Int): Single<List<Item>> {
    //do so things   
}

But in this case I can't do it because it has a List<Item> instead of Item. I want it to be in RXJava (don't want to run a method which loops the list and filter it)

How can I do it?


Solution

  • If getList() returns Single<List<Item>>, then I think flattenAsObservable is what you want:

    return getList()
        .flattenAsObservable { it -> it } // Turns it into Observable<Item>
        .filter { it -> it.age }
        .flatMap { addMoreData() }
        .map(mapper)
    

    You can also use .flatMapObservable { list -> Observable.fromIterable(list) }, but it's a little more verbose.