I followed the instructions in the following page and created a viewModel, but SavedStateHandle
does not work when I close the app and open it again.
Here is the page:
Saved State module for ViewModel
Here is my view model class:
class UserViewModel(private val state : SavedStateHandle) : ViewModel(){
val userId: LiveData<String> by lazy {
state.getLiveData("userId")
}
fun setUserId(userId : String) {
state["userId"] = userId
}
val user : User by lazy {
User("")
} }
Here is how I use the viewModel in my activity.
val userViewModel : UserViewModel by viewModels()
I even tried this one in my activity, but this did not work either!
val userViewModel: UserViewModel by viewModels {
SavedStateViewModelFactory(
application,
this
)
What should I do to persist data in the SavedStateHandle
? I mean, after opening the app state
is still empty.