Last active
May 27, 2019 06:15
-
-
Save polson/57ed47d7446c4674cb75a13bc443b6f1 to your computer and use it in GitHub Desktop.
Gist demonstrating how to get an ViewModel from your custom view
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
class MyView(context: Context) : FrameLayout(context) { | |
private val viewModel by lazy { setupViewModel() } | |
private val activity by lazy { scanForActivity(context) } | |
private fun scanForActivity(context: Context?): FragmentActivity = when (context) { | |
is FragmentActivity -> context | |
is ContextWrapper -> scanForActivity(context.baseContext) | |
else -> throw IllegalArgumentException("Context must be a FragmentActivity!") | |
} | |
private fun setupViewModel() = createViewModel(id.toString()) { | |
MyViewModel() | |
} | |
@Suppress("UNCHECKED_CAST") | |
private inline fun <reified T : ViewModel> createViewModel(key: String, crossinline initializer: () -> T): T { | |
val factory = object : ViewModelProvider.NewInstanceFactory() { | |
override fun <T : ViewModel?> create(modelClass: Class<T>): T = initializer() as T | |
} | |
return ViewModelProviders.of(activity, factory).get(key, T::class.java) | |
} | |
class MyViewModel : ViewModel() { | |
//TODO | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment