android - android View 模型之间的相互通信

标签 android mvvm android-architecture

我有一个客户详细信息页面,它从“客户”表加载客户详细信息并允许对某些详细信息进行一些编辑,其中一个是客户的位置。客户的位置是一个微调器,其中的下拉项是从“位置”表加载的。

所以我当前的实现是我有一个 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/

相关文章:

wpf - 如何在 UserControl 和父窗口之间绑定(bind) WPF 命令

在横向模式下锁定和解锁后,Android Lifecycle ViewModel 不会保留

java - 如何通过单击 ListView 中的项目转到另一个 fragment ?

android - 列表下方的按钮未显示

android - Sencha Touch 究竟是如何包装原生应用的?

wpf - 如果 View 和 View 模型之间不使用数据绑定(bind),MVVM 可以提供任何优势吗?

wpf - Caliburn - 异常处理和救援

android - 我可以将 Room Persistence 用于不同类型的数据库吗?

android - 事件包装器模式是否取代了 SingleLiveEvent 的使用?

android - 是否可以在图书馆项目中使用 Dagger?