Is it safe to call `requireContext()`/`requireActi...
# android
b
Is it safe to call `requireContext()`/`requireActivity()` in a
LiveData
observer?
n
As long as the observer is scoped with the view, I don’t think there is any problem
b
How do I know if it scoped with the view?
t
Whenever you call
Copy code
myLiveData.observe(this, Observer { ... })
where
this
is your
Activity
or
Fragment
, you're ensured that the
Observer
is tied to the lifecycle of that Activity/Fragment, i.e. it will unregister itself in
onDestroy()
. Otherwise, it will be unsafe to reference a
Context
in that
Observer
if you register it with
Copy code
myLivedata.observeForever(observer)
, unless you unregister that observer with
removeObserver(observer)
(but if you do that in a Fragment, why wouldn't you use
observe
instead ?)