Looking through the samples I seen 2 approaches to MVVM using Android Architecture Components.
First approach:
ViewModelprovidesLiveDataActivitysubscribes toLiveData- When observer called
Activityis setting data toViewModelObservableField. - Whole
ViewModelis passed to binding. -
In
xmlyou just setObservableFieldas value<ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" app:visibleGone="@{viewmodel.listLoading}"/> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent" app:refreshing="@{viewmodel.listRefreshing}" app:onRefreshListener="@{() -> viewmodel.refreshList()}" app:visibleGone="@{!viewmodel.listLoading}">
Pros: I don't need to pass state (for example "loading"), as I update listLoading ObservableField in ViewModel as this:
val listLoading = ObservableBoolean(false)
/** other observable fields go here **/
val list: MutableLiveData<List<Item>> = MutableLiveData()
fun loadList() {
listLoading.set(true)
repo.getList { items ->
list.value = items
listLoading.set(false)
}
}
Cons: Are there any cons in this approach?
Second approach:
ViewModelprovidesLiveDataActivitysubscribes toLiveData- When observer called
Activityis passed to binding - Only needed object (pojo) is passed to binding
Pros: Any pros of this approach?
Cons: State should be returned from ViewModel. In this sample from Google data is wrapped in Resource object.
First approach is used in another sample app from Google
I would like to know what are pros and cons of both patterns from developers with more experience working with Android Data Binding and Android Arch Components.
Aucun commentaire:
Enregistrer un commentaire