I'm a beginner with Dagger and am looking for the best way to handle a singleton User object that contains a user token.
I have several Manager class where User is injected (see below). However, my concern is about the way the value of User may change during the app lifecycle : when signing in, login out or other operation, CredentialManager can perform instructions like this.user = new User(jsonResponse)
which change the user object in the CredentialManager but not in UploaderManager (because the User injected reference has been overwritten with the new User). I created a copy method to avoid that : this.user.copy(new User(jsonResponse))
, but I find it unclean and difficult to maintain.
How would you suggest to handle that? Before I used Dagger, I used a singleton-pattern like User.getInstance()
and it was fine, but I try to improve my code for testing purpose. Thanks
@Singleton
public class CredentialManager {
private User user;
@Inject
public CredentialManager(User user) {
this.user = user;
}
}
@Singleton
public class UploaderManager {
private User user;
@Inject
public UploaderManager(User user) {
this.user = user;
}
}
@Singleton
public class User {
private String id;
@Inject
public User() {
/// ...
}
}
You can update user object with new user instance, copying user object is not fitting to your situation. And also with this solution you can still parse user object from json and update existing singleton object.
@Singleton
public class User {
private String userId;
@Inject
public User() {
}
public void update(User user){
this.userId = user.userId;
}
}