Orbit
Orbit

Reputation: 2375

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?

Upvotes: 6

Views: 16939

Answers (2)

Adam Dye
Adam Dye

Reputation: 471

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

Upvotes: 16

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

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

Upvotes: 3

Related Questions