Looking through the samples I seen 2 approaches to MVVM using Android Architecture Components.
First approach:
ViewModel
providesLiveData
Activity
subscribes toLiveData
- When observer called
Activity
is setting data toViewModel
ObservableField
. - Whole
ViewModel
is passed to binding. -
In
xml
you just setObservableField
as 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:
ViewModel
providesLiveData
Activity
subscribes toLiveData
- When observer called
Activity
is 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