Hi fellow droidheads! I've come across a new chall...
# android
e
Hi fellow droidheads! I've come across a new challenge with AndroidX Fragments and live data and I wonder if you can confirm the following 'rules': - If you use
androidx.fragment
artifacts v1.2.0 and up, AND - If you observe
LiveData
in fragments, AND - If that fragment does inflate a view in
onCreateView
AND - If that view is not null THEN use
viewLifecycleOwner
to observe live data. OTHERWISE use the fragment itself, which is a
LifecycleOwner
, to observe live data. Is this correct?
1
1
The difficult part is that the linter in my current version of AS doesn't help me with this: it shows nothing at all about this. This can lead to nasty crashes at runtime. There is a new lint rule in
androidx.fragment
v1.2.0, but it doesn't seem to work on my (and a colleague's) machine.
a
Actually I have the same situation and would like to know if it is the case
a
you can probably assume something simpler than that: if your observer influences views, use
viewLifecycleOwner
, if it does not, use the fragment itself
👍 3
e
That's a better rule of thumb. This seems to confirm this: https://issuetracker.google.com/issues/148238906
Also: if you use the fragment as the
LifecycleOwner
that observes, then observe in
onCreate
.
a
Where you observe from doesn't matter too much. You could observe from an
init
block too if you felt so inclined.
Where you observe with
viewLifecycleOwner
does matter though, as it gets recreated if the views are recreated
(since destroyed is defined as a terminal state)
e
My use case is an observer that modifies a view in an activity's menu. But the fragment is doing this. The fragment itself isn't inflating a view. Probably I've just discovered that that's a bit of an odd use case...
a
I would recommend against modifying views that you don't directly own
👍 1
e
Because according to what you say, which makes sence, my observer should use
viewLifecycleObserver
because it modifies a menu's views on observations
OK, thanks for the advice
a
my implication was views that are owned by the fragment, because a fragment should not modify views it does not own at all 🙂
e
Lucky for me that I didn't write this part of the code base, but also luckily this new lint situation pointed out the code smell
🙂 1