Dagger Android Tutorial 3

How to do dagger-android

Guowei Lv

1 minute read

Inject Retrofit @Singleton

The Retrofit instance should be a singleton in the scope of AppComponent.

Provide the Retrofit instance in AppModule.

@Singleton
@Provides
static Retrofit provideRetrofitInstance() {
    return new Retrofit.Builder().baseUrl(Constants.BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create()).build();
}

Under AuthActivity subcomponent, create a module called AuthModule, in it, provides the AuthApi instance.

@Module
public class AuthModule {
    @Provides
    static AuthApi provideAuthApi(Retrofit retrofit) {
        return retrofit.create(AuthApi.class);
    }
}

public interface AuthApi {

    @GET("/users/{id}")
    Flowable<User> getUser(@Path("id") int id);
}
@ContributesAndroidInjector(modules = {AuthModule.class, AuthViewModelsModule.class})
abstract AuthActivity contribute();

Now let’s try to fetch a user in AuthViewModel.

public class AuthViewModel extends ViewModel {

    private static final String TAG = "AuthViewModel";

    private final AuthApi authApi;

    @Inject
    AuthViewModel(AuthApi authApi) {
        this.authApi = authApi;
        authApi.getUser(1).toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(User user) {
                        Log.d(TAG, "onNext: " + user.getEmail());
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

Code for this article can be found here

comments powered by Disqus