Cem
Cem

Reputation: 158

RxJava - Mapping a result of list to another list

I want to convert every object in my list to an another object. But in doing so my code stucks in converting them back to List

override fun myFunction(): LiveData<MutableList<MyModel>> {
    return mySdk
            .getAllElements() // Returns Flowable<List<CustomObject>>
            .flatMap { Flowable.fromIterable(it) }
            .map {MyModel(it.name!!, it.phoneNumber!!) }
            .toList() //Debugger does not enter here
            .toFlowable()
            .onErrorReturn { Collections.emptyList() }
            .subscribeOn(Schedulers.io())
            .to { LiveDataReactiveStreams.fromPublisher(it) }
}

Everything is fine until mapping. But debugger does not even stop at toList or any other below toList. How can I solve this?

Upvotes: 3

Views: 4255

Answers (2)

Cem
Cem

Reputation: 158

Here is my solution to this. Thanks to Tim for leading me to right answer.

override fun myFunction(): LiveData<MutableList<MyModel>> {
    return mySdk
            .getAllElements() // Returns Flowable<List<CustomObject>>
            .flatMapSingle { Observable.fromIterable(it).map { MyModel(it.name!!, it.phoneNumber!!) }.toList() }
            .toFlowable()
            .onErrorReturn { Collections.emptyList() }
            .subscribeOn(Schedulers.io())
            .to { LiveDataReactiveStreams.fromPublisher(it) }
}

Upvotes: 1

tynn
tynn

Reputation: 39843

Using flatMap() you'll only flatten the Flowable of lists to a single Flowable of the elements. Calling toList() on it requires the Flowable to complete and therefore you'll most likely never get there. If you only want to map the elements in the list and have an item with the new list emitted, you should do the mapping within flatMap() or maybe try using concatMap() to keep the order:

...
.concatMapSingle { list ->
    Observable.fromIterable(list).map {
        MyModel(it.name!!, it.phoneNumber!!)
    }.toList()
}
...

Upvotes: 6

Related Questions