Skip to content

Instantly share code, notes, and snippets.

@Marchuck
Last active June 29, 2020 08:21
Show Gist options
  • Save Marchuck/13c86c01883c60486e17ffc37d344859 to your computer and use it in GitHub Desktop.
Save Marchuck/13c86c01883c60486e17ffc37d344859 to your computer and use it in GitHub Desktop.
class CounterViewModelFactory(val name: String) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return CounterViewModel(name) as T
}
}
//inside activity
val viewModel: CounterViewModel by lazy {
ViewModelProvider(
MainActivity@ this,
CounterViewModelFactory("shared")
)[CounterViewModel::class.java]
}
//inside fragment
val viewModel: CounterViewModel by lazy {
ViewModelProvider(
requireActivity(),
CounterViewModelFactory("shared")
)[CounterViewModel::class.java]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment