Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alcarazolabs/4b75f86264e6e1c8e138879231120327 to your computer and use it in GitHub Desktop.
Save alcarazolabs/4b75f86264e6e1c8e138879231120327 to your computer and use it in GitHub Desktop.
ViewModel Extension
fun <T: ViewModel> T.createFactory() : ViewModelProvider.Factory {
val viewModel = this
@Suppress("UNCHECKED_CAST")
return object :ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModel as T
}
}
//fragments or activities
private val myViewModel by viewModels<MyViewModel> {
MyViewModel(MyRemoteDatasource(MyApi())).createFactory()
}
//Dependencies
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
//lifecycle
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment