Search code examples
androidkotlinlifecyclecoroutine

Why the fragment's context null inside lifecycleScope


I have trouble while using lifecycleScope inside fragment, I think if the fragment detached to activity, then the lifecycleScope will cancel the coroutine jobs.

I have read the lifecycleScope' code and I think that can not happen. The only things I can do is add a precondition "isAdded" to workaround with this.

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

this code throw

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

I wish there're someone can help me to explain the lifecycleScope's mechanism.


Solution

  • lifecycleScope (same way as lifecycle itself) of Fragment is not always had context, context available only after onAttach and before onDetach, in case of retaining Fragment is alive after onDetach, so context can be null.

    Because you not only access context, but also touching view, you should use viewLifecycleOwner.lifecycleScope, this will allow you to start coroutine in Fragment's View lifecycle, so you always have context and it cancels onDestroyView