MaaAn13
MaaAn13

Reputation: 258

RxJava 2 - filter list inside list objects

getData() returns a Single<ArrayList1> which has alot of objects inside, that also are ArrayListX. I want to recieve only those cars(ArrayList) that is not empty. Of course, results.filter { cars -> cars.size > 0 } will not work, as it returns list not boolean. How to achieve this in correct manner? P.S. Still learning rxjava, haha

val disposable = repository.getData()
                    .observeOn(AndroidSchedulers.mainThread())
                    .filter { results ->
                        results.filter { cars -> cars.size > 0 }
                    }
                    .subscribe({ searchResults ->
                       ...
                    }, { _ ->
                        ...
                    })
            compositeDisposable.add(disposable)

Upvotes: 1

Views: 1588

Answers (1)

akarnokd
akarnokd

Reputation: 69997

This works for me:

import io.reactivex.Single
import java.util.*

fun main(args: Array<String>) {

    val source = Single.just(Arrays.asList(
            Collections.emptyList(),
            Arrays.asList(1, 2),
            Collections.emptyList(),
            Arrays.asList(3, 4, 5)
    ));

    // Single<List<(Mutable)List<Int!>!>!>!
    val output = source.map({ items -> items.filter({ !it.isEmpty()} )})

    output.subscribe({ res -> System.out.println(res) })
}

prints

[[1, 2], [3, 4, 5]]

Upvotes: 1

Related Questions