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

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;
    }

}

In your module you would have

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

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 code
RestApiClassOfSomeSort instance = restApiProvider.getRestClient(RestApiClassOfSomeSort.class);
instance.// do what you need!

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