Group Group Group Group Group Group Group Group Group

Jetpack Saved State for ViewModel: Getting Started | raywenderlich.com

In this tutorial, you’ll learn how to used saved state library to preserve the state of an android application and thus improving the user experience.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5212210-jetpack-saved-state-for-viewmodel-getting-started

It was good. There are some improvements that can assist. to make it more concise and better.

  1. With the help of KTX we can define ViewModel using by viewModels()
    viewModel = ViewModelProviders.of(this, SavedStateViewModelFactory(this)).get(ShoppingListViewModel::class.java)

  2. getItems().value!!.add(itemName) // it also don’t notify the observers because of addition, so it make it more elegant it needs to be written in a way that observers can notify properly
    May be creating separate list and then updating the livedata by that list

it would be great if we can remove non-null assertions

  1. If we don’t have items it’s good to hide the recyclerview rather than rendering it with nothing

private fun loadShoppingLists() {
// 2
viewModel.loadShoppingList()
// 3
viewModel.getItems().observe(this, Observer<ArrayList> {
shoppingListAdapter = ShoppingListAdapter(viewModel.getItems().value ?: arrayListOf())
recyclerView.adapter = shoppingListAdapter
shoppingListAdapter.notifyDataSetChanged()
// simething like this
items?.apply{
shoppingListAdapter = ShoppingListAdapter(this)
recyclerView.adapter = shoppingListAdapter
shoppingListAdapter.notifyDataSetChanged()
}

})

}

Thanks

1 Like

Hi! Not sure if it’s just me but the Final project doesn’t work… the new items aren’t saved after restarting the app after process death.

@droidchef Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi @karlj

What is the API Version of your emulator?
This will only work on Android Version P and above.

Can you try and confirm if the problem still persists?

Hi @droidchef, I’m encountering this issue in Android 10 / API 29.