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!