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()
?
No, if you want to observe changes for this query during whole lifetime of your application process, you don't need to unsubscribe from it!
There is no sense to unsubscribe from Rx
Subscription
inonComplete()
because when you receiveonComplete()
,Subscription
already finished and calls tounsubscribe()
won't do anything with it.// P.S. Interesting use case for StorIO!
Hope your
User
class is immutable and has correctly overriddenequals()
andhashCode()
because it looks like that you're sharing it to all components of the app and more over any update ofusers
table updates the reference to the new object, so it may affect code that already works withuser
object and then grabs new one.