gpt4 book ai didi

java - 如何使其实时数据观察器基于用户点击事件工作并接受一些用户输入,但应该从 onCreate 开始观察?

转载 作者:行者123 更新时间:2023-12-01 18:13:05 25 4
gpt4 key购买 nike

我先改造了存储库,然后查看模型,然后查看,但是在单击按钮观察者时,没有在 onChanged 中观察到。 OnClicking on 按钮,一切正常。我在 logcat 中收到 API 响应,但在 onChanged 中它没有被调用!

手动许可证 key View 模型

代码:

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;


}
}

}

Activity - 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 方法,它可以在以下情况下工作,但问题是,我想在用户单击事件中执行并在提交按钮之前从编辑文本中获取值。另外,我不想在 View 模型本身中进行观察,因为我想要有关 Activity 的数据!

 public void init() {
if (mutableLiveData == null) {
manualLicenseRepository = ManualLicenseRepository.getInstance();
mutableLiveData = manualLicenseRepository.getLicenseData("QQQQQ", "null", 4);
}
}

再次说明:

问题是如果我在onCreate中编写观察语句,它不会根据用户点击事件进行观察。因为我只想在用户在编辑文本中填写值并提交按钮时调用存储库 API,那么只有我才能获取必须在存储库中传递的值以进行 API 调用并将该值传递给 API。

最佳答案

当你打电话时

mutableLiveData = manualLicenseRepository.getLicenseData(licenseKey, macAddress, productId);

您已经在 onCreate 中将 Activity 观察者设置为 mutableLiveData 的实例。在您设置 mutableLiveData 的新实例后,所有观察者都将取消订阅,因为之前的实例不再存在,因此您的观察者将不会收到任何结果。

向观察者发送数据的更好方法是 MutableLiveData.postValue(value)。在这种情况下,您只需向活跃观察者发布一个值,而不是创建新的实时数据实例并取消订阅观察者。

但是如果您只需要在用户按下按钮后获取一次许可证数据,您最好调用Room suspend function并获取要显示的纯数据

附注最好在 onViewCreated 中添加观察者,而不是在 onCreate 中

关于java - 如何使其实时数据观察器基于用户点击事件工作并接受一些用户输入,但应该从 onCreate 开始观察?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60427788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com