我有一个跟踪登录用户的单身人士。如果为空,我有一个getInstance()
从数据库中获取用户的方法。instance
我的问题是是否可以保持订阅打开,以便对数据库的任何更新都会自动更新instance
变量。
这是我的班级的样子:
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;
}
});
}
}
我一定要在unsubscribe
某个地方打电话吗?如果是在哪里?里面onComplete()
?