尝试停止计时器时出现问题。此计时器在FragmentViewModel中创建。 如果我离开该应用程序,计时器将继续运行。我正在寻找一种阻止他的方法,但是我无法从Fragments onStop()函数访问他,因为他是在ViewModel中创建的,而ViewModel仅在Fragments onCreate()函数中被引用。有人知道如何解决这个问题吗?
这是我创建ViewModel的方法(内置计时器):
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
谢谢!
答案 0 :(得分:0)
您可以使用ViewModels onCleared()
回调。
要了解何时调用此方法(以便您确定是否合适),请参阅此问题和答案When is the viewmodel onCleared called
答案 1 :(得分:0)
如果要基于生命周期事件在视图模型中执行某些操作,请使视图模型实现LifecycleObserver
接口,然后在视图模型中执行
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
// stop timer
}
在您的片段中,您在onCreateView
中做了
lifecycle.addObserver(viewmodel)