[英]HashMap of Retrofit Classes with Dagger
我是依赖注入的新手,我对此表示怀疑。 在我的应用程序中,我有一个HashMap来存储RetroFit的内置类(如缓存),但是现在我正使用Dagger转向DI,我想知道如何实现相同的行为。
我的代码:
private Map<String, Object> restInstances;
public <T> T getRestClient(Class<T> clazz) {
T client = null;
if ((client = (T) restInstances.get(clazz.getCanonicalName())) != null) {
return client;
}
client = restAdapter.create(clazz);
restInstances.put(clazz.getCanonicalName(), client);
return client;
}
从DI开始后,我的“模块”类为:
@Provides @Singleton
public JobManager providesJobManager(){
Configuration config = new Configuration.Builder(app)
.minConsumerCount(1).maxConsumerCount(3).loadFactor(3).customLogger(new CustomLogger() {
private static final String TAG = "JOBS";
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public void d(String text, Object... args) {
Log.d(TAG, String.format(text, args));
}
@Override
public void e(Throwable t, String text, Object... args) {
Log.e(TAG, String.format(text, args));
}
@Override
public void e(String text, Object... args) {
Log.e(TAG, String.format(text, args));
}
})
.consumerKeepAlive(120).build();
return new JobManager(app, config);
}
@Provides @Singleton
public RestAdapter providesRestAdapter()
{
restInstances = new HashMap<String, Object>();
return new RestAdapter.Builder()
.setEndpoint("http://192.168.0.23:9000/api")
.setLogLevel(RestAdapter.LogLevel.FULL).build();
}
那么,如何将这个“缓存”哈希值注入我的应用程序?
谢谢
您可以创建一个类,其唯一目的是提供rest接口类。 这是接口/实现
public interface RestApiProvider {
public <T> T getRestClient(Class<T> clazz);
}
public class RestApiProviderImpl implements RestApiProvider {
private Map<String, Object> restInstances = new HashMap<String, Object>();
private RestAdapter restAdapter;
@Inject
RestApiProvider(RestAdapter restAdapter) {
this.restAdapter = restAdapter;
}
public <T> T getRestClient(Class<T> clazz) {
T client = null;
if ((client = (T) restInstances.get(clazz.getCanonicalName())) != null) {
return client;
}
client = restAdapter.create(clazz);
restInstances.put(clazz.getCanonicalName(), client);
return client;
}
}
在您的模块中,您将拥有
@Provides @Singleton
public RestAdapter providesRestAdapter()
{
return new RestAdapter.Builder()
.setEndpoint("http://192.168.0.23:9000/api")
.setLogLevel(RestAdapter.LogLevel.FULL).build();
}
@Provides @Singleton
public RestApiProvider providesRestApiProvider(RestApiProviderImpl impl) {
return impl;
}
这种工作方式是将模块中的RestAdapter Provider用作RestApiProviderImpl实例中的依赖项。 现在,在任何需要获取RestApi类实例的地方,只需要注入RestApiProvider。
@Inject
RestApiProvider restApiProvider;
// Somewhere in your code
RestApiClassOfSomeSort instance = restApiProvider.getRestClient(RestApiClassOfSomeSort.class);
instance.// do what you need!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.