Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Created February 12, 2021 09:16
Show Gist options
  • Save marcellogalhardo/8577a2b641221d3ae91f3ff63f0878c6 to your computer and use it in GitHub Desktop.
Save marcellogalhardo/8577a2b641221d3ae91f3ff63f0878c6 to your computer and use it in GitHub Desktop.
A small sample of ViewModel for Views. Not production ready. :D
inline fun <reified VM : ViewModel> View.getViewModel(): VM {
check(isAttachedToWindow) { "ViewModel can be accessed only when View is attached." }
val lifecycleOwner = lifecycleOwner
check(lifecycleOwner is ViewModelStoreOwner)
check(lifecycleOwner is HasDefaultViewModelProviderFactory)
return ViewModelProvider(lifecycleOwner, lifecycleOwner.defaultViewModelProviderFactory)
.get(id.toString(), VM::class.java)
}
@PublishedApi
internal val View.lifecycleOwner: LifecycleOwner
get() {
var found = lifecycleOwnerTag
if (found != null) {
return found
}
var currentParent = parent
while (found == null && currentParent is View) {
val parentView = currentParent as View
found = parentView.lifecycleOwnerTag
currentParent = parentView.parent
}
return found ?: context as LifecycleOwner
}
private val View?.lifecycleOwnerTag: LifecycleOwner?
get() {
return this?.getTag(R.id.fragment_container_view_tag) as? LifecycleOwner
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment