Reputation: 228
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
Upvotes: 1
Views: 4002
Reputation: 2335
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.
Upvotes: 1
Reputation: 1489
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.
Upvotes: 0