-
-
Save hasanmohdkhan/08230354e8475812720e27022bfe6474 to your computer and use it in GitHub Desktop.
Optimizing ViewModel with Lifecycle 2.2.0: Passing Arguments/Parameters
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
// Override ViewModelProvider.NewInstanceFactory to create the ViewModel (VM). | |
class SomeViewModelFactory(private val someString: String): ViewModelProvider.NewInstanceFactory() { | |
override fun <T : ViewModel?> create(modelClass: Class<T>): T = SomeViewModel(someString) as T | |
} | |
class SomeViewModel(private val someString: String) : ViewModel() { | |
init { | |
//TODO: Use 'someString' to init process when VM is created. i.e. Get data request. | |
} | |
} | |
class Fragment: Fragment() { | |
// Create VM in activity/fragment with VM factory. | |
// Don't forget to add 'kotlinOptions { jvmTarget = '1.8' } to build.gradle (:app)' | |
val someViewModel: SomeViewModel by viewModels { SomeViewModelFactory("someString") } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment