当应用程序启动时,我正在尝试从本地房间数据库加载loggedInUser 。如果之前保存的用户保存的身份验证令牌仍然有效,我想跳过提示用户登录!
因此,从DAO中,我想返回一个包含先前登录的用户的LiveData对象,然后观察它以进行后续更改。我面临的挑战是,如果我将结果包装在LiveData中,获取当前登录用户的方法总是返回 null,但如果返回为POJO ,它将返回预期的用户。
如何强制LiveData同步运行以初始化值,然后收听后续更改?我真的想结合这两种行为,因为身份验证可能会因后台同步任务或用户注销而失效(这些操作将替换或更新保存的令牌,我希望在实时数据)。
这是我到目前为止所尝试的:
AuthorizationDAO.java
public interface AuthorizationDAO {
@Query("SELECT * FROM Authorization LIMIT 1") //Assume only one Authentication token will exist at any given time
LiveData<Authorization> getLoggedInUser(); //I want to keep this behaviour
@Insert(onConflict = REPLACE)
long insertAuth(Authorization authorization);
@Update
void logoutCurrentUser(Authorization authorization);
}
AuthorizationRepository.java
public class AuthorizationRepository {
private AuthorizationDAO mAuthorizationDAO;
private MutableLiveData<Authorization> mAuthorization = new MutableLiveData<>();
public AuthorizationRepository(Application application){
AppDatabase db = AppDatabase.getDatabase(application);
this.mAuthorizationDAO = db.mAuthorizationDAO();
}
public LiveData<Authorization> getLoggedInUser(){
mAuthorization.postValue(mAuthorizationDAO.getLoggedInUser().getValue()); //this is always null at startup
return this.mAuthorization;
}
AuthorizationViewModel.java
public class AuthorizationViewModel extends AndroidViewModel {
private AuthorizationRepository mAuthorizationRepository;
private LiveData<Resource<Authorization>> mAuthorization;
private LiveData<Authorization> loggedInUserAuth;
public AuthorizationViewModel(@NonNull Application application) {
super(application);
this.mAuthorizationRepository = new AuthorizationRepository(application);
});
如您所见,我正在调用mAuthorizationViewModel.init()以便我可以从本地数据库加载或初始化loggedInUserAuth,然后在下一行使用mAuthorizationViewModel.getLoggedInUserAuth().observe()观察相同的LiveData实例!但是为loggedInUserAuth返回的值始终为 null!
请帮忙,谢谢!
手掌心
慕标琳琳
智慧大石
相关分类