java如何使实时数据观察程序基于用户点击事件工作,并获取一些用户输入,但应该从onCreate开始观察?
我先改造了存储库,然后查看模型,然后查看,但在点击“观察者”按钮时,并没有在onChanged中进行观察。从onClick点击按钮,一切正常。我在logcat中得到API响应,但在onChanged中它没有被调用
ManualLicenseKeyViewModel
代码:
public class ManualLicenseKeyViewModel extends ViewModel {
public MutableLiveData<String> key = new MutableLiveData<>();
private MutableLiveData<License> mutableLiveData;
private ManualLicenseRepository manualLicenseRepository;
public void init() {
if (mutableLiveData == null) {
manualLicenseRepository = ManualLicenseRepository.getInstance();
}
}
public LiveData<License> getLicenseRepository() {
return mutableLiveData;
}
private void getLicenseData(String licenseKey, String macAddress, int productId) {
mutableLiveData = manualLicenseRepository.getLicenseData(licenseKey, macAddress, productId);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_submit:
try {
getLicenseData(key.getValue(), "null", FIXED_PRODUCT_ID);
} catch (NullPointerException e) {
e.printStackTrace();
}
break;
}
}
}
活动-onCreate:
protected void init() {
manualLicenseKeyViewModel.init();
manualLicenseKeyViewModel.getLicenseRepository().observe(this, this);
}
@Override
public void onChanged(License license) {
showLog("Working?");
try {
showLog("license: " + license.getLicensekey());
} catch (Exception e) {
}
}
注意:如果我传入init方法,它在下面的情况下工作,但问题是,我想在用户单击事件中执行,并在提交按钮之前从编辑文本中获取值。此外,我不想观察视图模型本身,因为我想要活动的数据
public void init() {
if (mutableLiveData == null) {
manualLicenseRepository = ManualLicenseRepository.getInstance();
mutableLiveData = manualLicenseRepository.getLicenseData("QQQQQ", "null", 4);
}
}
再次解释:
问题是,如果我在onCreate中编写observe语句,它将不会基于用户单击事件进行观察。因为我只想在用户在edit text and submit按钮中填充值时调用存储库API,所以只有我才能获得值,我必须将该值传递到存储库中才能进行API调用,并将该值传递给API
# 1 楼答案
在你打电话的时候
您已经将
onCreate
中的活动观察者设置为mutableLiveData
的实例。设置mutableLiveData
的新实例后,所有观察者都将被取消订阅,因为上一个实例已不存在,因此你的观察者将不会收到任何结果向观察者发送数据的更好方式是
MutableLiveData.postValue(value)
。在这种情况下,您只需向活动的观察者发布一个值,而不是创建新的实时数据实例和取消订阅观察者但如果在用户按下按钮后只需要获取一次许可证数据,那么最好调用Room suspend function并获取要显示的普通数据
另外,最好在onViewCreated而不是onCreate中添加观察者