Search code examples
androiddependency-injectiondaggerobject-graph

Android Dagger updating values outside module


I am using dagger for DI in an android application. I can provide variables to other classes outside the modules, but how to update them?

Example: Login

I need a AuthenticationModule which can Provide a User. When the app starts, the User is not logged in, so it is null. But after successful authentication, LoginActivity needs to set the value of the User to make it accessible through other parts of the app via AuthenticationModule.

Simply setting the values of the injected field does not do the job for me.

Is it even possible?


Solution

  • I had simillar problem and I've made something like this:

    wrapper:

    class LoggedUserProvider {
        private User user;
        User getLoggedUser() {
            return user;
        }
        void setLoggedUser(User user) {
            this.user = user;
        }
    }
    

    module:

    @Module(injects = Endpoint.class)
    public class AuthenticationModule {
        @Provides
        @Singleton
        LoggedUserProvider provideLoggedUserProvider() {
            return new LoggedUserProvider();
        }
    }
    

    After that you can use @Inject LoggedUserProvider and just use getter/setter to set which user is currently logged in.

    OR

    If you want to make this without wrapper I guess you would need to make this module:

    @Module(injects = Endpoint.class)
    public class AuthenticationModule {
        @Provides
        User provideUser() {
            return null;
        }
    }
    

    and this but don't include this before authorization:

    @Module(overrides = true)
    public class CurrentUserModule {
        User currentUser;
        public CurrentUserModule(User currentUser) {
            this.currentUser = currentUser;
        }
    
        @Provides
        @Singleton
        User provideUser() {
            return currentUser;
        }
    }
    

    then, after authorization add this module to objectGraph (passing logged user to constructor) and recreate whole graph.
    That's just idea, I have never make it this way.