Should I include LifecycleOwner in ViewModel?

后端 未结 2 490
心在旅途
心在旅途 2020-12-29 23:28

LifecycleOwner is currently needed in order for me to create an observer.

I have code which creates an Observer in the ViewModel so I attach the LifecycleOwner when

相关标签:
2条回答
  • 2020-12-30 00:00

    Assumptions:

    1. Fuel refers to your ViewModel
    2. Fuel.request(IpAddressApi.MyIp()) is a method in your ViewModel
    3. IpAddressApi.MyIp() does not have a reference to your LifecycleOwner,

    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

    0 讨论(0)
  • 2020-12-30 00:03

    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.

    0 讨论(0)
提交回复
热议问题