Skip to content

Instantly share code, notes, and snippets.

@BenHenning
Created October 1, 2019 16:25
Show Gist options
  • Save BenHenning/77edecadc8209ae86b7119dfe51fb5fb to your computer and use it in GitHub Desktop.
Save BenHenning/77edecadc8209ae86b7119dfe51fb5fb to your computer and use it in GitHub Desktop.
class ListItemViewModel(val skillDescription: String): BaseObservable {
// Needs to be @Bindable?
var isChecked: Boolean = false
}
...
list_item.xml
<checkbox
android:id="@+id/skill_selected_checkbox"
android:checked="@={viewModel.isChecked}"
... />
...
Adapter's data structure is now a List<ListItemViewModel> which means that list_item's data binder expects a
ListItemViewModel to bind. Because this model is mutable, we can retrieve the isChecked states when the submit
button is clicked.
To automatically change the enabled state of the submit button, we could either use a Listener from ListItemViewModel
or an observer on it. Conceivably, there's a recyclerview view model that we're using as well:
class RecyclerViewParentViewModel: Observer @Inject constructor() {
val adapterData: List<ListItemViewModel> by lazy { createListItemViewModel() }
// Bindable?
val canContinue: Boolean = false
override fun update(Observable o, Object arg) {
val listItemViewModel = o as ListItemViewModel
canContinue = canContinue || listItemViewModel.isChecked // Automatically notifies observers if changes
}
private fun createListItemViewModel(): List<ListItemViewModel> {
val items: List<ListItemViewModel> = ...
// WARNING: we have to remove the observer otherwise it creates a cycle in the reference graph which will leak all
// the item views.
items.forEach { it.addObserver(RecyclerViewParentViewModel::this) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment