Reputation: 331
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?
Upvotes: 1
Views: 1152
Reputation: 331
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.
Upvotes: 3