【发布时间】:2019-09-03 11:45:59
【问题描述】:
我有以下活动类:
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。如何解决?
【问题讨论】:
-
您需要在 ViewModel 上观察
nameMutableLiveData或使用 onCompletion 接口返回字符串名称的值。您在收到 Firebase 的响应之前返回 LiveData,这是一个异步调用,因此没有任何发布价值的意义。 -
@Shermano 这不是我在做什么,使用
splashViewModel.nameLiveData.observe(...)观察nameMutableLiveData对象吗?其次,我会尽快在回调中发布该值。有没有其他办法? -
我感觉这样不行,你应该改用 MeaditorLiveData,但我不太确定,也许有人可以更好地帮助你,干杯
-
你说我应该使用
MediatorLiveData而不是MutableLiveData?刚刚遇到了同样的问题。
标签: android firebase google-cloud-firestore android-livedata android-viewmodel