转换单个&lt;List&lt;Item&gt;&gt;到 Observable<Item>? [英] Transform a Single&lt;List&lt;Item&gt;&gt; to an Observable&lt;Item&gt;?

查看:27
本文介绍了转换单个&lt;List&lt;Item&gt;&gt;到 Observable<Item>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网络请求调用中得到一个 Single>.最后,我想将这些项目用作 ObservableSingle>.我从 ItemItem2new 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 的参数是 Observables 而不是 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()

这篇关于转换单个&lt;List&lt;Item&gt;&gt;到 Observable<Item>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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