为什么片段的上下文在lifecycleScope中为空

Tou*_*gee 2 lifecycle android coroutine kotlin

我在片段中使用lifecycleScope时遇到麻烦,我认为如果该片段脱离活动,则lifecycleScope将取消协程作业。

我已经阅读了lifecycleScope的代码,但我认为这不可能发生。我唯一能做的就是为此添加一个先决条件“ iFyre”。

private fun updateUserInfo(user: User) = lifecycleScope.launch {
   textView.text = getString(R.string.foo)
}
Run Code Online (Sandbox Code Playgroud)

此代码抛出

java.lang.IllegalStateException androidx.fragment.app.Fragment.requireContext(Fragment.java:696)

我希望有人可以帮助我解释lifecycleScope的机制。

gil*_*dor 5

Fragment的lifecycleScope(与生命周期本身的方式相同)并不总是具有上下文,只有在onAttach之后和onDetach之前上下文才可用,如果保留Fragment在onDetach之后仍然存在,则上下文可以为null。

因为您不仅要访问上下文,而且还要访问视图,所以应该使用viewLifecycleOwner.lifecycleScope,这将允许您在Fragment的View生命周期中启动协程,因此您始终具有上下文,并且它会取消onDestroyView