在主要活动中,我无法在ViewModel的MutableLiveData属性上调用getValue();但是,我可以在ViewModel类内。是什么原因呢?
示例代码:主要活动-
noodleViewModel = ViewModelProviders.of(this).get(NoodleViewModel.class);
noodleViewModel.indexOfItemSelected.observe(this, index ->
{
Toast.makeText(this, String.format("This is the index: %d", index.intValue()), Toast.LENGTH_SHORT).show();
);
ViewModel内部类-
public int getPosition() {
return indexOfItemSelected.getValue();
}
答案 0 :(得分:1)
您已经在观察LiveData,因此lambda的index
参数已经是您要寻找的值
noodleViewModel.indexOfItemSelected.observe(this, index -> {
index == noodleViewModel.indexOfItemSelected.getValue() // should return true
}