Last active
February 18, 2018 14:53
-
-
Save muthuraj57/fb231c607c169a8c73918180441d0157 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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