6

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

所以我目前的实现是我有一个 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 执行顺序可能不同(有时客户加载速度更快,而其他位置加载速度更快)。

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

4

2 回答 2

0

听起来您想要类似于 RxJava 的combineLatest 运算符的东西。

您可以使用MediatorLiveData.

于 2018-03-06T00:34:15.233 回答
0

是的,您可以使用标志。

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
              }
        }
      });
   }
}
于 2017-12-21T04:05:17.743 回答