I have a singleton that keeps track of the logged in user. I have a getInstance()
method that fetches the user from the database if instance
is null. My question is if it is ok to keep the subscription open so that any updates to the database will automatically update the instance
variable.
Here is what my class looks like:
public class CurrentUser {
private static User instance;
private CurrentUser(){
//Singleton
}
public static void init(){
getCurrentuserFromDatabase();
}
public static User getInstance(){
if(instance == null){
getCurrentuserFromDatabase();
}
return instance;
}
private static void getCurrentuserFromDatabase(){
DatabaseModule.getStorIOSQLite()
.get()
.object(User.class)
.withQuery(
//Select a user from the User table whose session token is not null and is not empty
Query.builder()
.table(UsersTable.TABLE)
.where(UsersTable.COLUMN_SESSION_TOKEN + "IS NOT NULL AND " +
UsersTable.COLUMN_SESSION_TOKEN + " != \"\"")
.build())
.prepare()
.createObservable()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.newThread())
.subscribe(new Observer<User>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//user wasn't logged in
}
@Override
public void onNext(User user) {
instance = user;
}
});
}
}
Should I definitely be calling unsubscribe
somewhere? If so where? Inside onComplete()
?