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.

static Retrofit provideRetrofitInstance() {
    return new Retrofit.Builder().baseUrl(Constants.BASE_URL)

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

public class AuthModule {
    static AuthApi provideAuthApi(Retrofit retrofit) {
        return retrofit.create(AuthApi.class);

public interface AuthApi {

    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;

    AuthViewModel(AuthApi authApi) {
        this.authApi = authApi;
                .subscribe(new Observer<User>() {
                    public void onSubscribe(Disposable d) {


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

                    public void onError(Throwable e) {


                    public void onComplete() {


Code for this article can be found here

comments powered by Disqus