Ignacio Giagante Ignacio Giagante - 11 months ago 49
Android Question

convert Observable<RealmResults<T>>> into Observable<List<T>>>

I trying to implement the pattern Repository using Realm and RxJava. The repository interface has a signature like this

Observable<List<T>> query(Specification specification);

So, when I am working with Realm and would like to retrieve the result "asObservable", I get Observable>. I couldn't find a way to transform Observable> into Observable>.

Can anybody give a hand to resolve this?

I tried sth like this

final Observable<RealmResults<PlantRealm>> realmResults = realm.where(PlantRealm.class)
.equalTo(PlantTable.ID, "1")

// convert Observable<RealmResults<PlantRealm>> into Observable<List<PlantRealm>>

return realmResults.flatMap(Observable::from).toList().map(list -> {

for (PlantRealm plantRealm : list) {
return Observable.from(plants);

But the type check system is still complaining....

return Observable.create( subscriber -> {

final Realm realm = Realm.getInstance(realmConfiguration);
final RealmResults<PlantRealm> realmResults = realm.where(PlantRealm.class)
.equalTo(PlantTable.ID, "1")

final List<Plant> plants = new ArrayList<>();

for (PlantRealm plantRealm : realmResults) {




After watching Dan Lew's Conference about Common RxJava Mistakes (mistake flattening list), I found a common mistake related to this case.

So, the solution for this case is the following.

realmResults.flatMap(list ->
                    .map(plantRealm -> toPlant.map(plantRealm))

This video is awesome, I highly recommend to watch it.

I'm having problem with this solution if I want to access to the realm object from other Thread. I could resolve other corner case like this, but I'm still stuck with this.