Last active
September 4, 2020 20:13
-
-
Save adam-hurwitz/37e22ee6d8f1c7a74ab15d26a377d9b2 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
// See: [Optimizing Android ViewModel with Lifecycle 2.2.0](https://proandroiddev.com/optimizing-viewmodel-with-lifecycle-2-2-0-a2895b5c01fd) | |
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") } | |
} |
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 SomeViewModel(private val someString: String) : ViewModel() { | |
init { | |
//TODO: Use 'someString' to init process when VM is created. i.e. Get data request. | |
} | |
} |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment