Sunday, 7 October 2018

Will it cause resource leakage if I have a long life LifeCycleOwner keep observing LiveData?

In certain case like Home Widget (AppWidgetProvider), I don't have access to Activity or Fragment.

Usually, I use ProcessLifecycleOwner.get(), or the following LifeCycleOwner to observe LiveData.

public enum ForeverStartLifecycleOwner implements LifecycleOwner {
    INSTANCE;

    private final LifecycleRegistry mLifecycleRegistry;

    ForeverStartLifecycleOwner() {
        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

In most situation, in the callback of LiveData, I will try to remove LifeCycleOwner from further observing LiveData, by using liveData.removeObserver.

However, there are situation where

  1. LiveData fails to trigger callback.
  2. Hence, I didn't remove LifeCycleOwner from LiveData in LiveData's callback.

In such situation, will it cause resource leakage? For instance, GC notice a long life LifeCycleOwner is observing LiveData A. Although LiveData A is already out of scope, GC will not free-up LiveData A, because a long living LifeCycleObserver still observing it?

If so, how can I resolve this kind of leakage?



from Will it cause resource leakage if I have a long life LifeCycleOwner keep observing LiveData?

No comments:

Post a Comment