简体   繁体   中英

Transform a Single<List<Item>> to an Observable<Item>?

Goal

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

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.
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. In this case, you need to transform list into observable that sequentially emits items using .toObservable().flatMap(...) to change the type of the observable.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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