Avi Cohen
Avi Cohen

Reputation: 33

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?

Upvotes: 3

Views: 396

Answers (1)

dano
dano

Reputation: 94871

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.

Upvotes: 2

Related Questions