java 从 Flowable 一次发出一个列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44373463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Emit one List item at a time from a Flowable
提问by Orbit
I have a method which returns a Flowable<RealmResults<MyClass>>. For those not familiar with Realm, RealmResultsis just a simple Listof items.
我有一个方法返回一个Flowable<RealmResults<MyClass>>. 对于那些不熟悉 Realm 的人来说,RealmResults只是一个简单List的项目。
Given a Flowable<RealmResults<MyClass>>, I'd like to emit each MyClassitem so that I can perform a map()operation on each item.
给定 a Flowable<RealmResults<MyClass>>,我想发出每个MyClass项目,以便我可以map()对每个项目执行操作。
I am looking for something like the following:
我正在寻找类似以下内容:
getItems() // returns a Flowable<RealmResults<MyClass>>
.emitOneAtATime() // Example operator
.map(obj -> obj + "")
// etc
What operator will emit each List item sequentially?
哪个运算符将按顺序发出每个 List 项?
回答by Adam Dye
You would flatMap(aList -> Flowable.fromIterable(aList)). Then you can map()on each individual item. There is toList()if you want to recollect the items (note: this would be a new List instance). Here's an example illustrating how you can use these methods to get the different types using List<Integer>.
你会的flatMap(aList -> Flowable.fromIterable(aList))。然后你可以map()在每个单独的项目上。还有toList(),如果你想回忆的物品(注:这将是一个新的List实例)。这是一个示例,说明如何使用这些方法使用List<Integer>.
List<Integer> integerList = new ArrayList<>();
Flowable<Integer> intergerListFlowable =
Flowable
.just(integerList)//emits the list
.flatMap(list -> Flowable.fromIterable(list))//emits one by one
.map(integer -> integer + 1);
回答by Tassos Bassoukos
The question is, do you want to keep the results as a Flowable<List<MyClass>>or as a Flowable<MyClass>with retained order?
问题是,您希望将结果保留为保留顺序Flowable<List<MyClass>>还是Flowable<MyClass>保留顺序?
If the first,
如果第一个,
getItems()
.concatMap(results -> Flowable
.fromIterable(results)
.map(/* do your mapping */)
.toList()
)
If the second, this should suffice:
如果是第二个,这应该就足够了:
getItems()
.concatMap(Flowable::fromIterable)
.map(/* do your mapping */)

