1

I have followed the instructions in Google Codelab about the Saved state module.

My gradle dependency is:

implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc03"

My View Model factory is:

class MyViewModelFactory(val repository: AppRepository, owner: SavedStateRegistryOwner,
                              defaultArgs: Bundle? = null) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {

    override fun <T : ViewModel?> create(
            key: String,
            modelClass: Class<T>,
            handle: SavedStateHandle): T {
        return MyViewModel(repository, handle) as T
    }
}

My View model:

 class MyViewModel constructor(val repository: AppRepository, private val savedStateHandle: SavedStateHandle): ViewModel() {
       fun getMyParameter(): LiveData<Int?> {
            return savedStateHandle.getLiveData(MY_FIELD)
        }

        fun setMyParameter(val: Int) {
            savedStateHandle.set(MY_FIELD, val)
        }
    }

My Fragment:

      class MyFragment : androidx.fragment.app.Fragment() {
           override fun onCreate(savedInstanceState: Bundle?) {        
                arguments?.let {
                   var myField = it.getInt(MY_FIELD)
 activitiesViewModel.setMySavedValue(myField ?: 0)
                }

        }
        }

When the app is being used, the live data for the saved state field updates correctly. But as soon as I put the app in background (and I set "don't keep activities" in developer options), and then re open app, the live data shows a value as if it was never set. In other words, the saved state handle seems to forget the field I am trying to save.

Any thoughts?

Rowan Gontier
  • 821
  • 9
  • 14
  • i think for your scenario "don't keep activities in developer options", you should use `onSaveInstanceState` and `onRestoreInstanceState` , view model can save state when you have configuration change . checkout this article : https://medium.com/better-programming/architecture-viewmodel-vs-saveinstancestate-179f44d16c1 – Mojtaba Haddadi Jan 17 '20 at 07:39
  • In the article, it i said that in event of activity kill, "use save state/ restore state, OR you can use StateSaveHandle, which was introduced this year.". I am using the State save handle in view model, so it should work? – Rowan Gontier Jan 17 '20 at 22:49
  • Another thing that is unexpected, is that when the app re opens, the MY_FIELD key still exists in the state saved handle, but the value is wrong. – Rowan Gontier Jan 17 '20 at 23:09

1 Answers1

2

I had the same problem. It was solved by the fact that I stopped requesting saved values from SavedStateHandle in the onRestoreInstanceState method. This call is correctly used in the onCreate method.