In my Android project I am using the following Retrofit ApiModule
for one API end point. Please note, I use Dagger for injecting dependencies.
@Module(
complete = false,
library = true
)
public final class ApiModule {
public static final String PRODUCTS_BASE_URL = "https://products.com";
@Provides
@Singleton
Endpoint provideEndpoint() {
return Endpoints.newFixedEndpoint(PRODUCTS_BASE_URL);
}
@Provides
@Singleton
ObjectMapper provideObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
return objectMapper;
}
@Provides
@Singleton
RestAdapter provideRestAdapter(
Endpoint endpoint, ObjectMapper objectMapper) {
return new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.NONE)
.setEndpoint(endpoint)
.setConverter(new JacksonConverter(objectMapper))
.build();
}
@Provides
@Singleton
ProductsService provideProductsService(RestAdapter restAdapter) {
return restAdapter.create(ProductsService.class);
}
}
Now, there is another API (e.g. "http://subsidiaries.com"
) which I want to communicate with. Is it possible to extend the given ApiModule
while reusing the ObjectMapper
and the RestAdapter
? Or should I not extend it? I already tried to duplicate the module. But this involves that I have to duplicate the Endpoint
, ObjectMapper
and ... the RestAdapter
has a private contructor - so I can't.
I guess you could work with
Named
annotations:Now everywhere where you inject
ProductsService
you need to either annotate the dependency with@Named(PRODUCTS)
or@Named(SUBSIDIARIES)
, depending on which variant you need. Of course instead of the@Named
annotations you could also create your own, custom annotations and use them. See here under "Qualifiers".To flatten your module a bit you could move the creation of the RestAdapters into the
provide*Service()
methods and get rid of theprovide*RestAdapter()
methods. Unless you need the RestAdapters as a dependency outside of the module, of course.