2017-05-18 24 views
0

不确定这是否甚至可能,但我试图将自定义缓存策略实现为使用Realm的缓存。不幸的是,将实体复制到Realm响应主体需要扩展RealmObject。很明显,我的所有响应主体都这样做,但Response和ResponseBody在拦截时不知道响应类的类型。在Retrofit2拦截器中获取响应类类型(缓存为Realm)

我想这样做(但后来实施的缓存策略):

httpClient.addInterceptor(new Interceptor() { 
     @Override 
     public Response intercept(Chain chain) throws IOException { 
      Request request = chain.request(); 
      Response response = chain.proceed(request); 
      // Somewhere here will be the caching strategy 
      Realm.getDefaultInstance().copyToRealmOrUpdate(response.body()); 
      return response; 
     } 
    }); 

首先 - 是它甚至可能吗?如果是,那么如何。我没有看到任何明显的解决方案。如果这是不可能的,我需要在API的消费者客户端级别做缓存...

+0

你打开本地Realm实例,你将永远无法关闭这可能会导致问题,如果在后台非循环线程上完成,这可能是考虑这是一个网络请求的拦截器; – EpicPandaForce

+0

@EpicPandaForce您说得对,我应该在工作完成后关闭它,但这不是问题的重点。不过谢谢你! – Necroqubus

+0

@Necroqubus:建议是否有效?如果是这样,你能接受吗? ...或者,如果不是的话,你能否提出一个替代方案? –

回答

1

那么你可以尝试如下:

httpClient.addInterceptor(new Interceptor() { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request(); 
     Response response = chain.proceed(request); 
     // Somewhere here will be the caching strategy 
     Object object = response.body(); 
     if(object != null) { 
      try(Realm r = Realm.getDefaultInstance()) { 
       r.executeTransaction((realm) -> { 
        realm.copyToRealmOrUpdate((RealmObject)object); 
       }); 
      } 
     } 
     return response; 
    } 
}); 

虽然我不能保证它会工作。