Skip to content Skip to sidebar Skip to footer

Hashmap Of Retrofit Classes With Dagger

I'm kinda new to Dependency Injection and I have a doubt. In my app I have a HashMap to store built classes (like a cache) for RetroFit, but now I'm moving to DI with Dagger and I'

Solution 1:

You could create a class which it's sole purpose would be to provide rest interface classes. Here's the interface / implementation

publicinterfaceRestApiProvider {
    public <T> T getRestClient(Class<T> clazz);
}

publicclassRestApiProviderImplimplementsRestApiProvider {
    privateMap<String, Object> restInstances = newHashMap<String, Object>();
    privateRestAdapter restAdapter;

    @InjectRestApiProvider(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;
    }

}

In your module you would have

@Provides@SingletonpublicRestAdapterprovidesRestAdapter()
{
    returnnewRestAdapter.Builder()
            .setEndpoint("http://192.168.0.23:9000/api")
            .setLogLevel(RestAdapter.LogLevel.FULL).build();
}

@Provides@SingletonpublicRestApiProviderprovidesRestApiProvider(RestApiProviderImpl impl) {
    return impl;
}

The way this works is the the RestAdapter Provider from your module would be used as dependency in your RestApiProviderImpl instance. Now anywhere you'd need to get a RestApi class instance you'd simply need to inject your RestApiProvider.

@Inject
RestApiProvider restApiProvider;

// Somewhere in your codeRestApiClassOfSomeSortinstance= restApiProvider.getRestClient(RestApiClassOfSomeSort.class);
instance.// do what you need!

Post a Comment for "Hashmap Of Retrofit Classes With Dagger"