Inter communication between android viewmodels
Asked Answered
P

2

6

I have a customer detail page which load's a customer detail from "customer" table and allow some editing to some details, one which is customer's location. The customer's location is a spinner which drop down item is loaded from "location" table.

So my current implementation is I have a CustomerActivity which have a CustomerViewModel and 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);
        }
      });
   }
}

My question is how do I set the location spinner with the value from "customer" table since both the onChanged from both viewmodels executed order may differ (sometimes customer loads faster while other locations load faster).

I'd considered loading the locations only after the customer is loaded, but is there anyway I can load both concurrently while populating the customer's location spinner with the value from "customer" table?

Peacoat answered 21/12, 2017 at 3:30 Comment(0)
B
0

Yes, you can by using flags.

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
              }
        }
      });
   }
}
Belly answered 21/12, 2017 at 4:5 Comment(0)
F
0

It sounds like you want something similar to RxJava's combineLatest operator.

You can implement your own version using MediatorLiveData.

Faceless answered 6/3, 2018 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.