onActivityCreated is deprecated, how to properly use LifecycleObserver?
As per the changelog here
The
onActivityCreated()
method is now deprecated. Code touching the fragment's view should be done inonViewCreated()
(which is called immediately beforeonActivityCreated()
) and other initialization code should be inonCreate()
. To receive a callback specifically when the activity'sonCreate()
is complete, aLifeCycleObserver
should be registered on the activity's Lifecycle inonAttach()
, and removed once theonCreate()
callback is received.
You can do something like this in your fragment class:
class MyFragment : Fragment(), LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreated() {
// ... Your Logic goes here ...
}
override fun onAttach(context: Context) {
super.onAttach(context)
activity?.lifecycle?.addObserver(this)
}
override fun onDetach() {
activity?.lifecycle?.removeObserver(this)
super.onDetach()
}
}
All I needed was onActivityCreated(...)
, hence I did implement an observer that:
- Automatically removes itself (using
.removeObserver(...)
). - Then calls passed callback (
update()
).
I did it in next way:
class MyActivityObserver(
private val update: () -> Unit
) : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
owner.lifecycle.removeObserver(this)
update()
}
}
and use it in fragments onAttach (or another lifecycle method) like:
myActivity.lifecycle.addObserver(MyActivityObserver {
myOnActivityCreated()
})