如何解决如何在android + viewModel中进行回调
您好,我正在尝试通过jetpack使用新的体系结构组件。 那么如何弃用AsyncTask,我该如何在android中进行回调以从后台线程获取结果。没有我的应用程序延迟
public void btnConfigurarClick(View v) {
btnConfigurar.setEnabled(false);
myViewModel.configurar(); // do in background resulting true or false
// how to get the result of it with a callback to set enable(true)
...
解决方法
回调的概念根据ViewModels转换为Subscribe / Publish。 在Acvitity / Fragment中,您需要订阅ViewModel内部存在的LiveData。 更改将在您观察时得到通知。
Ex:
Class SomeActivity : Activity{
fun startObservingDataChange(){
yourViewModel.someLiveData.observe(viewLifecycleOwner) { data ->
// Whenever data changes in view model,you'll be notified here
// Update to UI can be done here
}
}
}
Class SomeViewModel{
// Observe to this live data in the View
val LiveData<String> someLiveData;
// Update happens to live data in view model
}
您可以在this应用中了解有关体系结构组件的更多信息。