Issue
My project structure has a BaseActivity which is extended by multiple child activities, so the structure is like
BaseActivity
^
|
-------------------------------
| | |
ChildActivityA ChildActivityB ChildActivityC
I am using DataBinding with LiveData, and hence every time I need to set up the lifecycleOwner for the respective binding class i.e (in ChildActivityA)
val binding = DataBindingUtil.setContentView(R.layout.somelayout)
binding.lifecycleOwner = this@ChildActivityA
Now I need to repeat this boilerplate in each Activity, so instead I created a helper extension function to replace the above two lines i.e
fun <T : ViewDataBinding> BaseActivity.setDataBindingView(layoutId: Int): T {
val binding = DataBindingUtil.setContentView(this, layoutId)
binding.lifecycleOwner = this@BaseActivity
}
and then call in my ChildActivityA as
val binding = setDataBindingView(R.layout.someLayout)
As you can see the binding.lifecycleOwner is set to BaseActivity instead of the actual ChildActivityA, now will this cause any trouble? Will the binding.lifecycleOwner be still following the lifecycle of ChildActivityA?
Solution
this@ChildActivityA and this@BaseActivity refer to the same actual object in memory - there's only one activity object that exists. Therefore they're entirely equivalent.
Answered By - ianhanniballake
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.