RxJava-将列表结果映射到另一个列表 [英] RxJava - Mapping a result of list to another list

查看:186
本文介绍了RxJava-将列表结果映射到另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表中的每个对象转换为另一个对象.但是这样做时,我的代码陷入了将它们转换回列表的问题

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

在映射之前,一切都很好.但是调试器甚至不会在toList或toList下面的任何其他位置停止.我该如何解决?

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

推荐答案

使用flatMap()只能将列表的Flowable展平为单个元素Flowable.调用toList()要求完成Flowable,因此您很可能永远无法到达那里.如果您只想映射列表中的元素并有一个发出新列表的项目,则应在flatMap()内进行映射,或者尝试使用concatMap()保持顺序:

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

这篇关于RxJava-将列表结果映射到另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆