简体   繁体   中英

Get Generic type Realm Objects from Realm

The goal I want to accomplish is generic response caching via Realm. The API client uses Retrofit. In retrofit callback I want to cache the incoming responses in Realm. The callback is generic and I want to apply it to many Retrofit calls. The Callback class is similar to this

public class CachedApiCallback 
    <E extends RealmObject, T extends List<E>>
implements Callback<T> { ... }

The passed type parameters guarantee that E will extend RealmObject. I want to do something like this:

public void onSuccessfulResponse(Call<T> call, Response<T> response, int statusCode) { 
   /// some caching logic
   RealmResults<E> cachedData = realm.where( ???? ); 
}

And here is the problem, I can't use standard Realm approach. Is there any way to retrieve data using generic RealmObject class?

I found an okay solution that works so far - passing type class value in constructor and storing it in the callback instance.

public class CachedApiCallback<E extends RealmObject, T extends List<E>> implements Callback<T> {

    protected boolean paging;
    protected IListenable<List<E>> listener;
    protected Class<E> entityType;

    public CachedApiCallback(Class<E> entityType){
        this.entityType = entityType;
    }

    public void onSuccessfulResponse(Call<T> call, Response<T> response, int statusCode) {
        // ....
        RealmResults<E> cachedData = realm.where(entityType).findAll();
        // ....
    }
}

There probably is a cleaner solution, but this does the job done.

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