[英]LiveData onChanged called multiple times with the same data when using FirebaseAuth
[英]onChanged is never called when getting data from Firebase using LiveData
我有以下活动课程:
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
splashViewModel.nameLiveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String name) {
Log.d(TAG, name); //Isn't printing anything
}
});
}
}
这是我的视图模型类:
public class SplashViewModel extends ViewModel {
private SplashRepository repository;
MutableLiveData<String> nameLiveData;
@Inject
SplashViewModel(SplashRepository repository) {
this.repository = repository;
nameLiveData = repository.addNameToLiveData();
}
}
这是我的存储库类:
class SplashRepository {
MutableLiveData<String> addNameToLiveData() {
MutableLiveData<String> nameMutableLiveData = new MutableLiveData<>();
ref.document(uid).get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if(document.exists()) {
String name = document.getString("name");
Log.d(TAG, name); //Is printed out correctly
nameMutableLiveData.postValue(name);
}
}
});
return nameMutableLiveData;
}
}
我正在使用postValue()
将数据添加到LiveData
。 在回调中,它可以正确打印名称,但是在观察nameLiveData
对象时,甚至不会触发onChanged
。 如何解决呢?
仓库应该具有不可改变和可变的实时数据对象。仓库应该暴露不可改变的实时数据对象。 不可更改的对象将使用可更改的对象进行更新。 示例应用程序示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.