Home > Back-end >  How to keep viewModel state when fragment is destroyed?
How to keep viewModel state when fragment is destroyed?

Time:02-08

I have an issue with keeping the state of data in a viewModel. The viewModel that I have is initialised inside of the onViewCreated method like this:

val viewModel: PlayerViewModelImpl by viewModels {
            ViewModelFactory(
              PlayerRepositoryImpl(MockContentProviderImpl()),
              ClipsAudioPlayerImpl.getInstance(requireActivity()),
              storage
            )
          }

and whenever i go back, and then open the fragment again I lose all the data that was processed inside of the viewModel. Does anyone have an idea on how can I retain the data and state of the viewModel for this scenario? Also here is my ViewModelFactory class:

/**
 * Factory for view models.
 */
class ViewModelFactory(
  private val repository: PlayerRepository,
  private val player: ClipsAudioPlayer<ClipsModel>,
  private val storage: PreferencesStorage): ViewModelProvider.NewInstanceFactory() {

  override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T = PlayerViewModelImpl(repository,storage,player) as T
}

Any help will be very much appreciated! Thanks

CodePudding user response:

You can use SharedViewModel concept to resolve this problem. You can keep the ViewModel alive if it attached to activity.

From its name, SharedViewModel can share data between fragments, or activities.

What you are going to do is to:

Use activityViewModel delegate

Follow the official documentation you will find a proper example that solve your problem.

CodePudding user response:

You need to declare the scope of the ViewModel to a context greater than the Fragments.

val factory = ViewModelFactory(
    PlayerRepositoryImpl(MockContentProviderImpl()),
    ClipsAudioPlayerImpl.getInstance(requireActivity()),
    storage
)
viewModel = ViewModelProvider(requireActivity(),factory).get(PlayerViewModelImpl::class.java)

As long as the current activity isn't destroyed the ViewModel should be preserved.

  •  Tags:  
  • Related