I have confuse when using lifecycleScope in fragme...
# android
t
I have confuse when using lifecycleScope in fragment, why the fragment’s context is null inside lifecycleScope? I also asked this on stackoverflow, here is the link: https://stackoverflow.com/questions/56415530/why-the-fragments-context-null-inside-lifecyclescope
g
It’s make sense.
lifecycleScope
has lifecycle of fragment and it’s != to lifecycle of context or view
Answered on SO
t
Thanks, really helped!
g
Thanks, really help but seems I can’t upvote this with enough scorev
You can acceprt answer instead of upvote 😁
😁 1
t
First time ask question on stackoverflow and founded the accept button😂
And I also have a doubt in your answer, the lifecycleScope of Fragment starts from onCreate until onDestroy, are as I know these lifecycle’ events inside onAttach to onDetach? If in, when using lifecycleScope of Fragment it self may cause a update UI exceptions but not a IllegalStateException of empty context.
g
may cause a update UI exceptions but not a IllegalStateException of empty context
No, because this job may executing even when context is null
and context is null when fragment is detached
t
I mean that because the onDestroy event happen before onDetach, so the code inside lifecycleScope will be canceled before onDetach
g
So yes, onCreate initially called after onAttach initially, but context is not avavilable after onDetach and before next onAttach
I see what you mean
t
So why there is a IllegalStateException of empty context when I use the Fragment’s lifecycleScope…
g
huh
okay, so essentially fragment have context only after super.onCreateView, not directly related to onAttach/onDetach, I updated answer
e
with the new android support for coroutines in fragment you have
viewLifecycleOwner.lifecycleScope
which should follow the lifecycle of the view instead o the fragment and prevent this issues
g
yes, I already mentioned this on SO
I’m digging to source code of Fragment and Fragment manager and understand that I understand less and less 🙈
🤣 1
t
I try to use
viewLifecycleOwner.lifecycleScope
, but it throw a Exception before onCreateView() or after onDestroyView(), for protected the method be called in a safe way, how about the below way?
Copy code
fun foo() = viewLifecycleOwnerLiveData.value?.lifecycleScope?.launch {
}
g
Sure, it throws exception, and this is the whole point, do not start it out of view lifecycle
e
you can use:
viewLifecycleOwner.lifecycleScope.launchWhenCreated {  }
that way inside the coroutine you know that view state is atleast created
👍 1