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?
I had simillar problem and I've made something like this:
class LoggedUserProvider {
private User user;
User getLoggedUser() {
return user;
}
void setLoggedUser(User user) {
this.user = user;
}
}
@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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With