简体   繁体   English

转换单个 <List<Item> &gt;到可观察的 <Item> ?

[英]Transform a Single<List<Item>> to an Observable<Item>?

Goal 目标

I get a Single<List<Item>> from a network request call. 我从网络请求调用中获得了Single<List<Item>> At the end, I would like to use those items either as a Observable<Item2> or a Single<List<Item2>> . 最后,我想将这些项目用作Observable<Item2>Single<List<Item2>> I go from Item to Item2 with new Item2(Item item) . 我走的Item ,以Item2new Item2(Item item)

What I thought would work 我认为会起作用

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(//.../);

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. 我以为可以用map转换observables的类型,所以我不太明白为什么第二个map的参数是Observable<Item>而不是Item。
How could I achieve this properly? 我怎样才能正确地做到这一点?

If I understood correctly, you want to convert Single<List<Item>> into stream of Item2 objects, and be able to work with them sequentially. 如果我理解正确,则希望将Single<List<Item>>转换为Item2对象的流,并能够顺序使用它们。 In this case, you need to transform list into observable that sequentially emits items using .toObservable().flatMap(...) to change the type of the observable. 在这种情况下,您需要将列表转换为可观察的对象,然后使用.toObservable().flatMap(...)顺序发射项目以更改可观察对象的类型。

For example: 例如:

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();

To summarize: if you want to change the type of Observable , use .flatMap() 总结一下:如果要更改Observable的类型,请使用.flatMap()

There some methods to do that: 有一些方法可以做到这一点:

items.flatMapObservable(Observable::fromIterable).map(Item2::new).toList()

// or

items.toObservable.flatMap(Observable::fromIterable).map(Item2::new).toList()

// or

items.toObservable().flatMapIterable(Functions.identity()).map(Item2::new).toList()

The first one is the simplest. 第一个是最简单的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM