简体   繁体   中英

Stop a timer when Fragment onStop is called

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!

You can use the ViewModels onCleared() callback.

To get an understanding of when this is called (so you can decide if it's appropriate) please see this question and the answers When is the viewmodel onCleared called

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM