Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42758

Which is the correct LifeCycleOwner to be used to observe LiveData in AppWidgetProvider

I need to observe some LiveData in AppWidgetProvider (During onUpdate). I was wondering, which of the following is a more appropriate LifeCycleObserver to be used?

ForeverStartLifecycleOwner (Custom)

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.support.annotation.NonNull;

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;
    }
}

Or, should I use ProcessLifecycleOwner.get()?

Both works fine. But, which one is more appropriate?

Upvotes: 4

Views: 1471

Answers (1)

Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42758

Finally, I stick with the following solution. It works fine so far as I don't see any live crash report, or receiving complains from customers. However, if you know a better way, please let me know.

ForeverStartLifecycleOwner

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.support.annotation.NonNull;

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;
    }
}

Usage

public static <T> void ready(LiveData<T> liveData, LifecycleOwner lifecycleOwner, Callable<T> callable) {
    T t = liveData.getValue();
    if (t != null) {
        callable.call(t);
        return;
    }

    liveData.observe(lifecycleOwner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            liveData.removeObserver(this);
            callable.call(t);
        }
    });
}

public static void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
    MediatorLiveData<Result> resultLiveData = getResultLiveData(appWidgetId);

    ready(resultLiveData, ForeverStartLifecycleOwner.INSTANCE, result -> onUpdate(context, appWidgetManager, result.stickyNoteConfig, result.note));
}

Upvotes: 3

Related Questions