viewlifecycleowner vs this

Ibrahim Yilmaz
2 min readAug 22, 2019
Photo by NeONBRAND on Unsplash

Hi Android Fellas,

In this post, I would like to mention about two lifecycleowners in Fragment. Because as an Android Developer, we can easily use Fragment as a lifecycle owner and in some cases it can hurt!

Lets firstly check the life cycle of Fragment:

As we can see from the diagram onCreate and onDestroy called once. These are Fragment mainly life cycle methods. onCreateView and onDestroyView are called according to state of Fragment because they are mainly life cycle methods of the View in Fragment.

So If we use onCreate method for binding our LiveData. Yes we register once and it seems very good and lean:

liveData.observe(this, observer)

But what will happen when we navigate to another fragment and change the value of LiveData there and get back our previous fragment

In going back to the Fragment, we cannot get recent data in LiveData and we should request it.

So it seems that using Views’s LifeCycle methods are much more useful. But in that condition. Common mistake that we do is to use Fragment as a LifeCycle owner.