【问题标题】:Inter communication between android viewmodelsandroid viewmodels之间的交互
【发布时间】:2018-06-03 16:36:00
【问题描述】:

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

所以我目前的实现是我有一个 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);
        }
      });
   }
}

我的问题是如何使用“客户”表中的值设置位置微调器,因为两个视图模型的 onChanged 执行顺序可能不同(有时客户加载速度更快,而其他位置加载速度更快)。

我曾考虑仅在加载客户后加载位置,但无论如何我可以同时加载这两个位置,同时使用“客户”表中的值填充客户的位置微调器?

【问题讨论】:

    标签: android mvvm android-architecture


    【解决方案1】:

    是的,您可以使用标志。

    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
                  }
            }
          });
       }
    }
    

    【讨论】:

      【解决方案2】:

      听起来你想要类似于 RxJava 的 combineLatest operator 的东西。

      您可以使用MediatorLiveData 实现您自己的版本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-31
        • 2012-02-02
        • 2019-01-12
        • 1970-01-01
        • 2022-12-01
        • 2023-04-04
        • 1970-01-01
        • 2014-07-29
        相关资源
        最近更新 更多