Should I include LifecycleOwner in ViewModel?
Assumptions:
Fuel
refers to yourViewModel
Fuel.request(IpAddressApi.MyIp())
is a method in yourViewModel
IpAddressApi.MyIp()
does not have a reference to yourLifecycleOwner
,
If all are true,then you are not violating it. So long as you are not passing a LifecycleOwner
reference to the ViewModel
you are safe!
LifecycleOwner - relates to an Activity or Fragment as it owns the various Android Lifecycles e.g onCreate, onPause, onDestroy etc
No. If you wish to observe changes of some LiveData
inside your ViewModel
you can use observeForever()
which doesn't require LifecycleOwner
.
Remember to remove this observer on ViewModel
's onCleared()
event:
val observer = new Observer() {
override public void onChanged(Integer integer) {
//Do something with "integer"
}
}
...
liveData.observeForever(observer);
...
override fun onCleared() {
liveData.removeObserver(observer)
super.onCleared()
}
Very good reference with examples of observe LiveData.