https://kotlinlang.org logo
#android
Title
# android
b

bryan

02/07/2019, 6:40 PM
Is it safe to call `requireContext()`/`requireActivity()` in a
LiveData
observer?
n

nounours

02/07/2019, 6:44 PM
As long as the observer is scoped with the view, I don’t think there is any problem
b

bryan

02/07/2019, 6:50 PM
How do I know if it scoped with the view?
t

tseisel

02/11/2019, 9:15 PM
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 ?)
10 Views