Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
               .findAll().asObservable();

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

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

                for (PlantRealm plantRealm : list) {
                    plants.add(toPlant.map(plantRealm));
                }
                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")
               .findAll();

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

       for (PlantRealm plantRealm : realmResults) {
           plants.add(toPlant.map(plantRealm));
       }

       realm.close();

       subscriber.onNext(plants);
       subscriber.onCompleted();
   });
like image 902
Ignacio Giagante Avatar asked Apr 26 '16 19:04

Ignacio Giagante


1 Answers

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 ->
            Observable.from(list)
                    .map(plantRealm -> toPlant.map(plantRealm))
                    .toList())

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.

code

console

I resolved this...

resolved

like image 108
Ignacio Giagante Avatar answered Sep 18 '22 21:09

Ignacio Giagante