Skip to content

Instantly share code, notes, and snippets.

@muthuraj57
Last active February 18, 2018 14:53
Show Gist options
  • Save muthuraj57/fb231c607c169a8c73918180441d0157 to your computer and use it in GitHub Desktop.
Save muthuraj57/fb231c607c169a8c73918180441d0157 to your computer and use it in GitHub Desktop.
/*
* ViewModel variable name must be {{viewModel}}.
*
* Binds the viewModel to the DataBinding and clears the observable subscription
* on view detached from window.
* */
fun <T : ViewDataBinding, V : BaseViewModel> T.bindViewModel(viewModel: V): Boolean {
val bindSuccess = setVariable(BR.viewModel, viewModel)
if (bindSuccess) {
root.onAttachStateChanged(
{
viewModel.onDetach()
viewModel.onAttach()
},
{
viewModel.onDetach()
}
)
} else {
throw IllegalStateException("Binding $this view model variable name should be `viewModel`")
}
return bindSuccess
}
/*
* Calls the corresponding method based on initial state on setting the listener.
* */
inline fun View.onAttachStateChanged(
crossinline onAttach: () -> Unit,
crossinline onDetach: () -> Unit
) {
var isAttached = isAttachedToWindow
if (isAttached) {
onAttach()
}
addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewDetachedFromWindow(v: View?) {
if (isAttached) {
onDetach()
isAttached = false
}
}
override fun onViewAttachedToWindow(v: View?) {
if (!isAttached) {
onAttach()
isAttached = true
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment