我有以下活动课程:
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
。该如何解决?
答案 0 :(得分:0)
Repos应该具有不可更改的和可变的实时数据对象。Repo应该公开不可更改的实时数据对象,这将在视图模型中使用observeforever方法进行观察。 不可更改的对象将使用可更改的对象进行更新。 示例应用示例