Seb
Seb

Reputation: 3213

Observable Lists merge to a single observable List in Kotlin

I am building an Android app which gathering data with a specific argument. The app is developed in Java/Kotlin and based on RxJava.

class Cars constructor(val carsData: CarsData) {

  fun getCars(): Observable<List<Car>> {
    return listOf(
        carsData.getCar("toyota")
            .flatMap { Observable.from(it)}
            .distinct { it.productId }
            .toSortedList()
          ,
        carsData.getCar("chevrolet")
            .flatMap { Observable.from(it)}
            .distinct { it.productId }
            .toSortedList(),
        carsData.getCar("cadillac")
            .flatMap { Observable.from(it)}
            .distinct { it.productId }
            .toSortedList())

}

I want to return an Observable<List<Car>>. Any call to getCar is returning an Observable<List<Car>>. By default, I have an issue because I am returning an Observable<List<Observable<List<Car>>> because I need to extract the data first to merge everything.

Any idea, how to make it works? the code above is not working, because it's complaining about type issue and I assume it's linked to the mix of Observable.

Thanks for your help.

Upvotes: 0

Views: 1099

Answers (1)

zsmb13
zsmb13

Reputation: 89538

If you want to return an Observable that will emit these 3 lists in sequence, you can use Observable.merge or Observable.concat depending on whether you want to preserve their order:

return Observable.merge(
    carsData.getCar("toyota")
            .flatMap { Observable.from(it) }
            .distinct { it.productId }
            .toSortedList(),
    carsData.getCar("chevrolet")
            .flatMap { Observable.from(it) }
            .distinct { it.productId }
            .toSortedList(),
    carsData.getCar("cadillac")
            .flatMap { Observable.from(it) }
            .distinct { it.productId }
            .toSortedList()
)

Upvotes: 3

Related Questions