RxJava - Mapping a result of list to another list

妖精的绣舞 提交于 2020-01-24 19:25:07

问题


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?


回答1:


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()
}
...



回答2:


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) }
}



回答3:


override fun myFunction(): LiveData<MutableList<MyModel>> { return mySdk .getAllElements() .flatMap {it -> Flowable.fromIterable(it) it.map(MyModel(it.name!!, it.phoneNumber!!) ) } .toFlowable() .onErrorReturn { Collections.emptyList() } .subscribeOn(Schedulers.io()) .to { LiveDataReactiveStreams.fromPublisher(it) } }



来源:https://stackoverflow.com/questions/53317686/rxjava-mapping-a-result-of-list-to-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!