Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 387
Martin Golpashin Avatar asked Sep 02 '14 10:09

Martin Golpashin


2 Answers

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.

like image 92
WojciechKo Avatar answered Nov 16 '22 18:11

WojciechKo


By re-assigning the User-object itself over and over again, the ObjectGraph cannot pass the newly assigned object to other classes.

I solved the problem by implementing an AuthenticationHandler which holds the userobject. So there is only one Object that gets injected which implements methods like setCurrentUser()

like image 39
Martin Golpashin Avatar answered Nov 16 '22 18:11

Martin Golpashin