-
-
Save hasanmohdkhan/02e374875bc8b5adff1ad99e43c8e4e7 to your computer and use it in GitHub Desktop.
Optimizing ViewModel with Lifecycle 2.2.0: Passing Arguments/Parameters with SavedState
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 SomeViewModelFactory( | |
private val owner: SavedStateRegistryOwner, | |
private val defaultArgs: Bundle, | |
private val someString: String) : AbstractSavedStateViewModelFactory(owner, defaultArgs) { | |
override fun <T : ViewModel?> create(key: String, modelClass: Class<T>, state: SavedStateHandle) = | |
SomeViewModel(state, someString) as T | |
} | |
class SomeViewModel(private val state: SavedStateHandle, private val someString: String) : ViewModel() { | |
// The default value is used from 'defaultArgs' since 'defaultArgs' are saved in the ViewModelFactory. | |
val someInt = state.get<Int>(SOME_INT_KEY) | |
init { | |
//TODO: Use 'defaultString' and 'someString' to init process when VM is created. i.e. Get data request. | |
} | |
fun saveSomeInt(someInt: Int) { | |
state.set(SOME_INT_KEY, position) | |
} | |
} | |
class Fragment: Fragment() { | |
// Create VM in activity/fragment with VM factory. | |
// Don't forget to add "kotlinOptions { jvmTarget = '1.8' }" to "android" build.gradle (:app) | |
val someViewModel: SomeViewModel by viewModels { SomeViewModelFactory( | |
savedStateRegistryOwner = this, | |
defaultArgs = Bundle().apply { | |
putInt(SOME_INT_KEY, 18) | |
}, | |
someString = "someString") } | |
private var someInt: Int = 0 | |
override fun onSaveInstanceState(outState: Bundle) { | |
super.onSaveInstanceState(outState) | |
someViewModel.saveSomeInt(...) | |
} | |
override fun onViewStateRestored(savedInstanceState: Bundle?) { | |
super.onViewStateRestored(savedInstanceState) | |
someInt = someViewModel.someInt | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment