Forked from emedinaa/gist:e83d3d95deb6bcdd18071c52e5313f27
Created
July 7, 2022 20:18
-
-
Save alcarazolabs/4b75f86264e6e1c8e138879231120327 to your computer and use it in GitHub Desktop.
ViewModel Extension
This file contains 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
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 | |
} | |
} |
This file contains 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
//fragments or activities | |
private val myViewModel by viewModels<MyViewModel> { | |
MyViewModel(MyRemoteDatasource(MyApi())).createFactory() | |
} |
This file contains 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
//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