我有一个客户详细信息页面,它从“客户”表加载客户详细信息并允许对某些详细信息进行一些编辑,其中一个是客户的位置。客户的位置是一个微调器,其中的下拉项是从“位置”表加载的。
所以我当前的实现是我有一个 CustomerActivity,它有一个 CustomerViewModel 和 LocationViewModel
public class CustomerActivity extends AppCompatActivity {
...
onCreate(@Nullable Bundle savedInstanceState) {
...
customerViewModel.getCustomer(customerId).observe(this, new Observer<Customer>() {
@Override
public void onChanged(@Nullable Customer customer) {
// bind to view via databinding
}
});
locationViewModel.getLocations().observe(this, new Observer<Location>() {
@Override
public void onChanged(@Nullable List<Location> locations) {
locationSpinnerAdapter.setLocations(locations);
}
});
}
}
我的问题是如何使用“客户”表中的值设置位置微调器,因为两个 View 模型的 onChanged 执行顺序可能不同(有时客户加载速度更快,而其他位置加载速度更快)。
我考虑过仅在加载客户后才加载位置,但无论如何我都可以在使用“客户”表中的值填充客户的位置微调器的同时同时加载两者吗?
最佳答案
是的,您可以使用标志。
public class CustomerActivity extends AppCompatActivity {
private Customer customer = null;
private List<Location> locations = null;
...
onCreate(@Nullable Bundle savedInstanceState) {
...
customerViewModel.getCustomer(customerId).observe(this, new Observer<Customer>() {
@Override
public void onChanged(@Nullable Customer customer) {
// bind to view via databinding
this.customer = customer;
if(locations != null){
both are loaded
}
}
});
locationViewModel.getLocations().observe(this, new Observer<Location>() {
@Override
public void onChanged(@Nullable List<Location> locations) {
locationSpinnerAdapter.setLocations(locations);
this.locations = locations;
if(customer != null){
//customer and locations loaded
}
}
});
}
}
关于android - android View 模型之间的相互通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917520/