为什么片段的上下文在 lifecycleScope 中为 null
Why the fragment's context null inside lifecycleScope
我在片段内部使用 lifecycleScope 时遇到问题,我认为如果片段分离到 activity,那么 lifecycleScope 将取消协程作业。
我已经阅读了 lifecycleScope 的代码,我认为这不可能发生。
我唯一能做的就是添加一个先决条件 "isAdded" 来解决这个问题。
private fun updateUserInfo(user: User) = lifecycleScope.launch {
textView.text = getString(R.string.foo)
}
此代码抛出
java.lang.IllegalStateException androidx.fragment.app.Fragment.requireContext (Fragment.java:696)
希望有人能帮我解释一下lifecycleScope的机制。
Fragment的lifecycleScope(同生命周期本身)并不总是有context,context只有在onAttach之后onDetach之前可用,如果在onDetach之后保留Fragment还活着,那么context可以为null。
因为你不仅要访问context,还要接触view,所以你应该使用viewLifecycleOwner.lifecycleScope
,这样你就可以在Fragment的View生命周期中启动coroutine,所以你总是有context并且它取消了onDestroyView
我在片段内部使用 lifecycleScope 时遇到问题,我认为如果片段分离到 activity,那么 lifecycleScope 将取消协程作业。
我已经阅读了 lifecycleScope 的代码,我认为这不可能发生。 我唯一能做的就是添加一个先决条件 "isAdded" 来解决这个问题。
private fun updateUserInfo(user: User) = lifecycleScope.launch {
textView.text = getString(R.string.foo)
}
此代码抛出
java.lang.IllegalStateException androidx.fragment.app.Fragment.requireContext (Fragment.java:696)
希望有人能帮我解释一下lifecycleScope的机制。
Fragment的lifecycleScope(同生命周期本身)并不总是有context,context只有在onAttach之后onDetach之前可用,如果在onDetach之后保留Fragment还活着,那么context可以为null。
因为你不仅要访问context,还要接触view,所以你应该使用viewLifecycleOwner.lifecycleScope
,这样你就可以在Fragment的View生命周期中启动coroutine,所以你总是有context并且它取消了onDestroyView