转换单个<List<Item>>到 Observable- ?
我从网络请求调用中得到一个 Single
.最后,我想将这些项目用作 >
Observable
或 Single
.我从 >
Item
到 Item2
和 new Item2(Item item)
.
I get a Single<List<Item>>
from a network request call. At the end, I would like to use those items either as a Observable<Item2>
or a Single<List<Item2>>
. I go from Item
to Item2
with new Item2(Item item)
.
Single<List<Item>> items
.map(Observable::fromIterable) // Single<List> to Observable
.map(new Function<Observable<Item>, Observable<Item2>>() {
// I don't really know how I can do it here
})
.subscribeOn(//.../)
.observeOn(//.../);
我想我可以用 map
转换 observables
的类型,所以我不太明白为什么第二个 map
的参数是 Observable
s 而不是 Item.
我怎样才能正确地实现这一目标?
I thought I could transform the types of the observables
with map
, so I do not quite get why the parameters of the second map
are Observable<Item>
s and not Item.
How could I achieve this properly?
如果我没理解错,你是想把Single
转成>
Item2
代码> 对象,并能够按顺序使用它们.在这种情况下,您需要将列表转换为 observable,使用 .toObservable().flatMap(...)
更改可观察的类型.
If I understood correctly, you want to convert Single<List<Item>>
into stream of Item2
objects, and be able to work with them sequentially. In this case, you need to transform list into observable that sequentially emits items using .toObservable().flatMap(...)
to change the type of the observable.
例如:
Single<List<Item>> items = Single.just(new ArrayList<>());
items.toObservable()
.flatMap(new Func1<List<Item>, Observable<Item>>() {
@Override
public Observable<Item> call(List<Item> items) {
return Observable.from(items);
}
})
.map(new Func1<Item, Item2>() {
@Override
public Item2 call(Item item) {
return new Item2(item);
}
})
.subscribeOn(//.../)
.observeOn(//.../);
或者,使用方法引用可以使代码更加简单:
Or, using method references you can make this code even more simple:
items.toObservable()
.flatMap(Observable::from)
.map(Item2::new)
.subscribeOn(//.../)
.observeOn(//.../)
.subscribe();
总结:如果你想改变Observable
的类型,使用.flatMap()
To summarize: if you want to change the type of Observable
, use .flatMap()