Created
February 12, 2021 09:16
-
-
Save marcellogalhardo/8577a2b641221d3ae91f3ff63f0878c6 to your computer and use it in GitHub Desktop.
A small sample of ViewModel for Views. Not production ready. :D
This file contains hidden or 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
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