I've got a problem when I try to stop my timer. This timer is created in a FragmentViewModel. If I navigate away from the app, the timer keeps running. Im looking for a way to stop him, but I cant access him from the Fragments onStop() function, since hes created in the ViewModel, which only gets referenced in the Fragments onCreate() function. Anyone got an idea how to solve this problem?
This is how I create the ViewModel (with the timer inside):
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: GameFragmentBinding = DataBindingUtil.inflate(
inflater, R.layout.game_fragment, container, false)
val application = requireNotNull(this.activity).application
val dataSource = TranslationDB.getInstance(application).translationDBDao
val viewModelFactory = GameFragmentViewModelFactory(dataSource, application)
val gameFragmentViewModel =
ViewModelProviders.of(
this, viewModelFactory).get(GameFragmentViewModel::class.java)
binding.gameFragmentViewModel = gameFragmentViewModel
Thanks in advance!
If you want to execute some action in your viewmodel based on a lifecycle event, make your viewmodel implement the LifecycleObserver
interface, then in your viewmodel you do
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// stop timer
}
and in your fragment, in onCreateView
you do
lifecycle.addObserver(viewmodel)