I have this network module . I want to inject Network module in static method of ErrorUtils.
#Module
public class NetworkModule {
private final String END_POINT = "https://www.myurl.com/";
#Provides
#Singleton
public OkHttpClient getOkHttpClient() {
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
}
#Provides
#Singleton
public GsonConverterFactory getGsonConverterFactory() {
return GsonConverterFactory.create();
}
#Provides
#Singleton
public Retrofit getRetrofit(OkHttpClient okHttpClient, GsonConverterFactory gsonConverterFactory) {
return new Retrofit.Builder()
.baseUrl(END_POINT)
.client(okHttpClient)
.addConverterFactory(gsonConverterFactory)
.build();
}
#Provides
#Singleton
public RetrofitService getRetrofitService(Retrofit retrofit) {
return retrofit.create(RetrofitService.class);
}
And I want to inject this module in static method as :
public class ErrorUtils {
#Inject
static Retrofit retrofit;
public static RestError parseError(Response<?> response) {
**//showing error while writing this line**
MyApplication.getComponent().inject(ErrorUtils.class);
Converter<ResponseBody, RestError> converter = retrofit.responseBodyConverter(RestError.class, new Annotation[0]);
RestError error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new RestError();
}
return error;
}
}
How can we inject module in static method ,any suggestion ?
As can be seen in Migrating from Dagger 1
Dagger 2 does not support static injection.
Static methods and variables are generally a bad idea. In your case you could just make your ErrorUtils an object, e.g. with #Singleton scope. Then you could properly inject the service and also properly inject your errorUtils without the use of static calls.
If that is not an option, you can just provide a getter to your component
#Component interface MyComponent {
Retrofit getRetrofit();
}
And then use that method to set your static variable.
Related
I want to inject a Retrofit object directly into my MyRepository class but I always get a NullPointerException. This is what I have tried.
This is my AppModule class:
#Module
public class AppModule {
#Singleton
#Provides
static Retrofit provideRetrofitInstance(){
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
And this is my view model class:
public class MyViewModel extends AndroidViewModel {
LiveData<Data> myLiveData;
MyViewModel(Application application, City city) {
super(application);
myLiveData = myRepository.addDataToLiveData(city);
}
LiveData<Data> getLiveData() {
return myLiveData;
}
}
And this is my repository class where I want to inject Retofit:
public class MyRepository {
private String myTex;
#Inject
private Retrofit retrofit;
public MyRepository(String myText) {
this.myText = myText;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call using retrofit
}
}
Edit:
This is how I instantiate my ViewModel in my activity class:
MyRepository repository = new MyRepository("MyText");
Application application = activity.getApplication();
MyViewModelFactory factory = new MyViewModelFactory(application, repository);
MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);
Making your Repository injectable is the simplest solution, which also allows you to inject it where it's used, in your ViewModels or Interactors:
#Singleton
public class MyRepository {
private Retrofit retrofit;
#Inject
public MyRepository(Retrofit retrofit) {
this.retrofit = retrofit;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call using retrofit
}
}
Edit: you can either provide the text via Dagger and inject that in your constructor, like this
#Inject
public MyRepository(String myText, Retrofit retrofit)
Note that you'd need to use #Named or #Qualifier for your string.
Alternatively, you can inject your repository calling inject(this), the syntax depends on how you setup Dagger
somehowGetDaggerComponent().inject(this)
I strongly suggest you go with the 1st solution.
My field for retrofit in this class is never injected into, it is still null when i run my code.
Here is my ServiceClass where I inject retrofit, have my api calls etc. I stripped it down for simplicity:
public class ServiceClass{
#Inject
Retrofit retrofit;
public ServiceClass(){
}
}
My module class for all network related dependencies:
#Module
public class NetworkModule {
#Provides
#ApplicationScope
Retrofit getRetrofit(OkHttpClient okHttpClient, Gson gson){
return new Retrofit.Builder()
.baseUrl(URL.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
#Provides
#ApplicationScope
OkHttpClient getOkHttpClient(Gson gson, HttpLoggingInterceptor httpLoggingInterceptor){
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder().addInterceptor(httpLoggingInterceptor);
return okHttpClient;
}
#Provides
#ApplicationScope
HttpLoggingInterceptor getHttpLoggingInterceptor(){
return new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
}
#Provides
#ApplicationScope
Gson getGson(){
return new Gson();
}
}
My AppComponent this is my only component class:
#ApplicationScope
#Component(modules = {NetworkModule.class})
public interface AppComponent {
#Component.Builder
interface Builder {
#BindsInstance
Builder application(MyApplication myApplication);
AppComponent build();
}
void inject(MyApplication myApplication);
Retrofit getRetrofit();
}
My Application class:
public class MyApplication extends Application{
private AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
DaggerAppComponent
.builder()
.application(this)
.build()
.inject(this);
}
public AppComponent getAppComponent(){
return appComponent;
}
}
I tried to fiddle around the code, I don't seem to manage to get it working properly. What am I missing here?
Update (previous information still valid) :
I have noticed you incorrectly build your component: you must add .networkModule(new NetworkModule()) after DaggerAppComponent.builder()
Make sure your private AppComponent appComponent is initialized too!
For field injection (I believe that's what you're after), you can write your constructor like this:
public ServiceClass(){
MyApplication.getInstance().getAppComponent().inject(this)
}
Naturally, you should expose your appComponent entity somehow - the above is my guess (to expose appComponent entity via application entity).
PS.: better approach (and more readable too) is to avoid field injection at all and parametrize constructor (however it's not always possible, like for example if you inject into activity).
PSS.: your AppComponent should also have void inject(ServiceClass value);
There are multiple ways of injecting retrofit in ServiceClass
You have to make a separate Component for ServiceClass like :-
#Component(dependencies = AppComponent.class)
interface ServiceClassComponent {
void injectServiceClass(ServiceClass serviceClass);
}
Or
you can just inject ServiceClass into your application component:-
void injectServiceClass(ServiceClass serviceClass);
into your AppComponent
The dependencies keyword would include all the dependent components into your particular component that you would build.
Then in the constructor of ServiceClass you need to build the Component and inject it
Hey there I am using Dagger2, Retrofit and OkHttp and I am facing dependency cycle issue.
When providing OkHttp :
#Provides
#ApplicationScope
OkHttpClient provideOkHttpClient(TokenAuthenticator auth,Dispatcher dispatcher){
return new OkHttpClient.Builder()
.connectTimeout(Constants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constants.READ_TIMEOUT,TimeUnit.SECONDS)
.writeTimeout(Constants.WRITE_TIMEOUT,TimeUnit.SECONDS)
.authenticator(auth)
.dispatcher(dispatcher)
.build();
}
When providing Retrofit :
#Provides
#ApplicationScope
Retrofit provideRetrofit(Resources resources,Gson gson, OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl(resources.getString(R.string.base_api_url))
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
}
When providing APIService :
#Provides
#ApplicationScope
APIService provideAPI(Retrofit retrofit) {
return retrofit.create(APIService.class);
}
My APIService interface :
public interface APIService {
#FormUrlEncoded
#POST("token")
Observable<Response<UserTokenResponse>> refreshUserToken();
--- other methods like login, register ---
}
My TokenAuthenticator class :
#Inject
public TokenAuthenticator(APIService mApi,#NonNull ImmediateSchedulerProvider mSchedulerProvider) {
this.mApi= mApi;
this.mSchedulerProvider=mSchedulerProvider;
mDisposables=new CompositeDisposable();
}
#Override
public Request authenticate(Route route, Response response) throws IOException {
request = null;
mApi.refreshUserToken(...)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.doOnSubscribe(d -> mDisposables.add(d))
.subscribe(tokenResponse -> {
if(tokenResponse.isSuccessful()) {
saveUserToken(tokenResponse.body());
request = response.request().newBuilder()
.header("Authorization", getUserAccessToken())
.build();
} else {
logoutUser();
}
},error -> {
},() -> {});
mDisposables.clear();
stop();
return request;
}
My logcat :
Error:(55, 16) error: Found a dependency cycle:
com.yasinkacmaz.myapp.service.APIService is injected at com.yasinkacmaz.myapp.darkvane.modules.NetworkModule.provideTokenAuthenticator(…, mApi, …)
com.yasinkacmaz.myapp.service.token.TokenAuthenticator is injected at
com.yasinkacmaz.myapp.darkvane.modules.NetworkModule.provideOkHttpClient(…, tokenAuthenticator, …)
okhttp3.OkHttpClient is injected at
com.yasinkacmaz.myapp.darkvane.modules.NetworkModule.provideRetrofit(…, okHttpClient)
retrofit2.Retrofit is injected at
com.yasinkacmaz.myapp.darkvane.modules.NetworkModule.provideAPI(retrofit)
com.yasinkacmaz.myapp.service.APIService is provided at
com.yasinkacmaz.myapp.darkvane.components.ApplicationComponent.exposeAPI()
So my question: My TokenAuthenticator class is depends on APIService but I need to provide TokenAuthenticator when creating APIService. This causes dependency cycle error. How do I beat this , is there anyone facing this issue ?
Thanks in advance.
Your problem is:
Your OKHttpClient depends on your Authenticator
Your Authenticator depends on a Retrofit Service
Retrofit depends on an OKHttpClient (as in point 1)
Hence the circular dependency.
One possible solution here is for your TokenAuthenticator to depend on an APIServiceHolder rather than a APIService. Then your TokenAuthenticator can be provided as a dependency when configuring OKHttpClient regardless of whether the APIService (further down the object graph) has been instantiated or not.
A very simple APIServiceHolder:
public class APIServiceHolder {
private APIService apiService;
#Nullable
APIService apiService() {
return apiService;
}
void setAPIService(APIService apiService) {
this.apiService = apiService;
}
}
Then refactor your TokenAuthenticator:
#Inject
public TokenAuthenticator(#NonNull APIServiceHolder apiServiceHolder, #NonNull ImmediateSchedulerProvider schedulerProvider) {
this.apiServiceHolder = apiServiceHolder;
this.schedulerProvider = schedulerProvider;
this.disposables = new CompositeDisposable();
}
#Override
public Request authenticate(Route route, Response response) throws IOException {
if (apiServiceHolder.get() == null) {
//we cannot answer the challenge as no token service is available
return null //as per contract of Retrofit Authenticator interface for when unable to contest a challenge
}
request = null;
TokenResponse tokenResponse = apiServiceHolder.get().blockingGet()
if (tokenResponse.isSuccessful()) {
saveUserToken(tokenResponse.body());
request = response.request().newBuilder()
.header("Authorization", getUserAccessToken())
.build();
} else {
logoutUser();
}
return request;
}
Note that the code to retrieve the token should be synchronous. This is part of the contract of Authenticator. The code inside the Authenticator will run off the main thread.
Of course you will need to write the #Provides methods for the same:
#Provides
#ApplicationScope
apiServiceHolder() {
return new APIServiceHolder();
}
And refactor the provider methods:
#Provides
#ApplicationScope
APIService provideAPI(Retrofit retrofit, APIServiceHolder apiServiceHolder) {
APIService apiService = retrofit.create(APIService.class);
apiServiceHolder.setAPIService(apiService);
return apiService;
}
Note that mutable global state is not usually a good idea. However, if you have your packages organised well you may be able to use access modifiers appropriately to avoid unintended usages of the holder.
Using the Lazy interface of Dagger 2 is the solution here.
In your TokenAuthenticator replace APIService mApi with Lazy<APIService> mApiLazyWrapper
#Inject
public TokenAuthenticator(Lazy<APIService> mApiLazyWrapper,#NonNull ImmediateSchedulerProvider mSchedulerProvider) {
this.mApiLazyWrapper= mApiLazyWrapper;
this.mSchedulerProvider=mSchedulerProvider;
mDisposables=new CompositeDisposable();
}
And to get the APIService instance from wrapper use mApiLazyWrapper.get()
In case mApiLazyWrapper.get() returns null, return null from the authenticate method of TokenAuthenticator as well.
Big thanks to #Selvin and #David. I have two approach, one of them is David's answer and the other one is :
Creating another OkHttp or Retrofit or another library which will handle our operations inside TokenAuthenticator class.
If you want to use another OkHttp or Retrofit instance you must use Qualifier annotation.
For example :
#Qualifier
public #interface ApiClient {}
#Qualifier
public #interface RefreshTokenClient {}
then provide :
#Provides
#ApplicationScope
#ApiClient
OkHttpClient provideOkHttpClientForApi(TokenAuthenticator tokenAuthenticator, TokenInterceptor tokenInterceptor, Dispatcher dispatcher){
return new OkHttpClient.Builder()
.connectTimeout(Constants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constants.READ_TIMEOUT,TimeUnit.SECONDS)
.writeTimeout(Constants.WRITE_TIMEOUT,TimeUnit.SECONDS)
.authenticator(tokenAuthenticator)
.addInterceptor(tokenInterceptor)
.dispatcher(dispatcher)
.build();
}
#Provides
#ApplicationScope
#RefreshTokenClient
OkHttpClient provideOkHttpClientForRefreshToken(Dispatcher dispatcher){
return new OkHttpClient.Builder()
.connectTimeout(Constants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(Constants.READ_TIMEOUT,TimeUnit.SECONDS)
.writeTimeout(Constants.WRITE_TIMEOUT,TimeUnit.SECONDS)
.dispatcher(dispatcher)
.build();
}
#Provides
#ApplicationScope
#ApiClient
Retrofit provideRetrofitForApi(Resources resources, Gson gson,#ApiClient OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl(resources.getString(R.string.base_api_url))
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
}
#Provides
#ApplicationScope
#RefreshTokenClient
Retrofit provideRetrofitForRefreshToken(Resources resources, Gson gson,#RefreshTokenClient OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl(resources.getString(R.string.base_api_url))
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
}
Then we can provide our seperated interfaces :
#Provides
#ApplicationScope
public APIService provideApi(#ApiClient Retrofit retrofit) {
return retrofit.create(APIService.class);
}
#Provides
#ApplicationScope
public RefreshTokenApi provideRefreshApi(#RefreshTokenClient Retrofit retrofit) {
return retrofit.create(RefreshTokenApi.class);
}
When providing our TokenAuthenticator :
#Provides
#ApplicationScope
TokenAuthenticator provideTokenAuthenticator(RefreshTokenApi mApi){
return new TokenAuthenticator(mApi);
}
Advantages : You have two seperated api interfaces which means you can maintain them independently. Also you can use plain OkHttp or HttpUrlConnection or another library.
Disadvantages : You will have two different OkHttp and Retrofit instance.
P.S : Make sure you make syncronous calls inside Authenticator class.
You can inject the service dependency into your authenticator via the Lazy type. This way you will avoid the cyclic dependency on instantiation.
Check this link on how Lazy works.
I am learning Dagger 2 now and it's such a pain for me to explain the question without codes , so let me list all my modules, components and etc first :
App.class
public class App extends Application {
private ApiComponent mApiComponent = null;
private AppComponent mAppComponent = null;
public ApiComponent getApiComponent() {
if (mApiComponent == null) {
// Dagger%COMPONENT_NAME%
mApiComponent = DaggerApiComponent.builder()
// list of modules that are part of this component need to be created here too
.appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
.apiModule(new ApiModule(this))
.build();
}
return mApiComponent;
}
public AppComponent getAppComponent() {
if (mAppComponent == null) {
// If a Dagger 2 component does not have any constructor arguments for any of its modules,
// then we can use .create() as a shortcut instead:
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
return mAppComponent;
}
}
AppComponent
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(RetrofitDemo target);
}
AppModule
private final Application mContext;
AppModule(Application context) {
mContext = context;
}
#Singleton
#ForApplication
#Provides
Application provideApplication() {
return mContext;
}
#Singleton
#ForApplication
#Provides
Context provideContext() {
return mContext;
}
ApiComponent
#Singleton
#Component(dependencies = {AppModule.class},modules = {ApiModule.class})
public interface ApiComponent {
void inject(RetrofitDemo target);
}
APIModule
#Inject
Context application;
#Inject
public ApiModule(Context context){
this.application = context;
}
#Provides
#Singleton
Gson provideGson() {
return new GsonBuilder()
// All timestamps are returned in ISO 8601 format:
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
// Blank fields are included as null instead of being omitted.
.serializeNulls()
.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient() {
...
}
#Provides
#Singleton
public Retrofit provideRetrofit(Gson gson,OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl(DribbleApi.END_POINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
And my activity will be like this:
#Inject
Retrofit mRetrofit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit_demo);
((App) getApplication()).getApiComponent().inject(this);
...
Here is the error message:
Error:(18, 10) : retrofit2.Retrofit cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.
retrofit2.Retrofit is injected at com.sinyuk.yuk.RetrofitDemo.mRetrofit
com.sinyuk.yuk.RetrofitDemo is injected at com.sinyuk.yuk.AppComponent.inject(target)
What makes me confused is the retrofit instance is provided by the ApiModule, but why the error massage said it's injected at appComponent?And I can't find any place wrong in my code. T_T,it's too heavy going to learn Dagger for me...I think.
Besides, in my case I wrote dependencies = AppModule.class module = ApiModule.class in the AppComponent , and it seems to be right I think,but if I wrote module = ({AppComponent.class,ApiComponent.class}),it also works fine.Anybody can explain me why?
Kindly review my code and give me some advice. Thx in advance!
#Sinyuk There's a lot to unpack here, and Dagger is a little complicated at first blush, but I think I can help. First, you have a conceptual misunderstanding regarding the #Component annotation. A Component is an interface which you define, and which Dagger implements through code generation. You will define the interface, and annotate it with #Component and then you will provide a set of Modules to Dagger to use in the generation process. The modules which you use are passed in through the modules element of the #Component annotation. If you want to have one Component permit another Component to support the injection process, then any Component interfaces which you need to have Dagger use while injecting your code, will be passed in through the dependencies element of the #Component annotation.
--
As a result, The following is incorrect
#Component(dependencies = AppModule.class module = ApiModule.class`)
instead, to have the one Component use two Modules write:
#Component(modules = {ApiModule.class, AppModule.class})
or, to have one Component use one Module and depend upon the other Component
#Component(modules = {AppModule.class}, dependencies = {ApiComponent.class})
I hope that that helps you get onto the right path. Let me know if you have any follow up questions.
Okay so your configuration should be this
public class App extends Application {
private AppComponent mAppComponent = null;
public AppComponent getAppComponent() {
if (mAppComponent == null) {
// If a Dagger 2 component does not have any constructor arguments for any of its modules,
// then we can use .create() as a shortcut instead:
mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
return mAppComponent;
}
}
And
#Singleton
#Component(modules = {AppModule.class, ApiModule.class})
public interface AppComponent {
void inject(RetrofitDemo target);
}
And
#Module
public class AppModule {
private final Application mContext;
AppModule(Application context) {
mContext = context;
}
#Provides
Application provideApplication() {
return mContext;
}
#Provides
Context provideContext() {
return mContext;
}
}
And
#Module
public class ApiModule {
#Provides
#Singleton
Gson provideGson() {
return new GsonBuilder()
// All timestamps are returned in ISO 8601 format:
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
// Blank fields are included as null instead of being omitted.
.serializeNulls()
.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient() {
...
}
#Provides
#Singleton
public Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient){
return new Retrofit.Builder()
.baseUrl(DribbleApi.END_POINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okHttpClient)
.build();
}
}
And
//...Activity
#Inject
Retrofit mRetrofit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit_demo);
((App) getApplication()).getAppComponent().inject(this);
...
Currently I'm using Dagger 2 to inject an instance of Retrofit to use for an api call in a widget. From my understanding, Dagger searches for things to inject using the type, so declaring 2 seperate #Provides Retrofit providesRetrofit() with different names wouldn't work.
Heres my current code:
Module:
#Module
public class ApiModule {
#Provides
#Singleton
GsonConverterFactory provideGson() {
return GsonConverterFactory.create();
}
#Provides
#Singleton
RxJavaCallAdapterFactory provideRxCallAdapter() {
return RxJavaCallAdapterFactory.create();
}
#Singleton
#Provides
Retrofit providePictureRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MarsWeatherWidget.PICTURE_URL)
.addConverterFactory(gsonConverterFactory)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.build();
return retrofit;
}
....
//Here is the other Retrofit instance where I was wanting to use a different URL.
// #Singleton
// #Provides
// Retrofit provideWeatherRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(MarsWeatherWidget.WEATHER_URL)
// .addConverterFactory(gsonConverterFactory)
// .addCallAdapterFactory(rxJavaCallAdapterFactory)
// .build();
// return retrofit;
// }
}
Component:
#Singleton
#Component(modules = ApiModule.class)
public interface ApiComponent {
void inject (MarsWeatherWidget marsWeatherWidget);
}
class extending Application:
public class MyWidget extends Application {
ApiComponent mApiComponent;
#Override
public void onCreate() {
super.onCreate();
mApiComponent = DaggerApiComponent.builder().apiModule(new ApiModule()).build();
}
public ApiComponent getApiComponent() {
return mApiComponent;
}
}
and finally where im actually injecting it:
#Inject Retrofit pictureRetrofit;
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
mAppWidgetIds = appWidgetIds;
((MyWidget) context.getApplicationContext()).getApiComponent().inject(this);
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
}
}
......
//use the injected Retrofit instance to make a call
So how can I organize this to give me a seperate Retrofit instance that is built with different URLs for hitting different APIs? Let me know if more info is needed.
Provide different versions of the same type
You can use #Named (or custom annotations that are annotated with #Qualifier) to distinguish between variants of the same type.
Add the annotations like the following:
#Singleton
#Provides
#Named("picture")
Retrofit providePictureRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {
return retrofit = new Retrofit.Builder()
.baseUrl(MarsWeatherWidget.PICTURE_URL) // one url
.build();
}
#Singleton
#Provides
#Named("weather")
Retrofit provideWeatherRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {
return retrofit = new Retrofit.Builder()
.baseUrl(MarsWeatherWidget.WEATHER_URL) // other url
.build();
}
Custom #Qualifier
You could also just create a custom annotation like the following:
#Qualifier
#Retention(RUNTIME)
public #interface Picture {}
You would just use this instead of #Named(String).
Injecting the qualified version
When you have your module providing the qualified types, you just need to also add the qualifier where you need the dependency.
MyPictureService provideService(#Named("picture") Retrofit retrofit) {
// ...
}
You should use a qualifier annotation to distinguish between different objects that have the same type—like between the Retrofit for pictures and the Retrofit for weather.
You apply the same qualifier to the #Provides method and to the #Inject parameter (constructor or method parameter, or field).
#Named is one qualifier annotation, but using it means you have to remember to use the exact same string at the provision point and at all injection points. (It's easy to mistype #Named("whether") somewhere.)
But it's easy to define your own qualifier annotation. Just define a custom annotation type, and annotate that with #Qualifier:
#Documented
#Qualifier
public #interface Picture {}
#Documented
#Qualifier
public #interface Weather {}
Then you can bind each Retrofit differently:
#Provides #Picture Retrofit providePictureRetrofit(…) {…}
#Provides #Weather Retrofit provideWeatherRetrofit(…) {…}
and inject each where you need it:
#Inject #Picture Retrofit pictureRetrofit;
#Inject #Weather Retrofit weatherRetrofit;
// (But constructor injection is better than field injection!)