简体   繁体   中英

Emit one List item at a time from a Flowable

I have a method which returns a Flowable<RealmResults<MyClass>> . For those not familiar with Realm, RealmResults is just a simple List of items.

Given a Flowable<RealmResults<MyClass>> , I'd like to emit each MyClass item so that I can perform a map() operation on each item.

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?

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

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

The question is, do you want to keep the results as a Flowable<List<MyClass>> or as a Flowable<MyClass> with retained order?

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 */)

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