Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Orbit Avatar asked Jun 05 '17 16:06

Orbit


2 Answers

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);
like image 153
Adam Dye Avatar answered Sep 28 '22 02:09

Adam Dye


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 */)
like image 28
Tassos Bassoukos Avatar answered Sep 28 '22 03:09

Tassos Bassoukos