jakubkinst / Android-ViewModelBinding

A lightweight library aiming to speed up Android app development by leveraging the new Android Data Binding together with the Model-View-ViewModel design pattern.
294 stars 32 forks source link

Add aggregate view models. #18

Open karlsonj opened 6 years ago

karlsonj commented 6 years ago

This adds the ability to have viewmodels that contain other viewmodels. In the Android layout files, you might have, say, a (shared) widget that manages phone number entry and validation, and a viewmodel that contains it and manages the validation of the rest of a form. Something like this:

<layout>
  <data>
    <variable name="formViewModel" type="com.company.FormViewModel"/>
    <variable name="phoneViewModel" type="com.company.PhoneViewModel"/>
  </data>
  <LinearLayout>
    <!-- Bound components for the form... -->
    <include layout="@layout/phoneentry" app:viewModel="@{phoneViewModel}"/>
  </LinearLayout>
</layout>

This PR allows you to create an outer FormViewModel that extends AggregateViewModel and a shared PhoneViewModel that extends SubViewModel and is aggreagated within the FormViewModel:

class FormViewModel extends AggregateViewModel {

  PhoneViewModel phoneViewModel = new PhoneViewModel();

  class FormViewModel() {
    addSubviews(phoneViewModel);
  }
}