这是用于观察AppWidgetProvider中的LiveData的正确LifeCycleOwner

时间:2018-10-02 17:25:25

标签: android

我需要观察function getMax(arr) { let len = arr.length; let max = -Infinity; while (len--) { max = arr[len] > max ? arr[len] : max; } return max; } 中的一些LiveData(在AppWidgetProvider期间)。我想知道,以下哪个更适合使用onUpdate

ForeverStartLifecycleOwner(自定义)

LifeCycleObserver

或者,我应该使用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; } } 吗?

两者都很好。但是,哪个更合适?

1 个答案:

答案 0 :(得分:3)

最后,我坚持使用以下解决方案。就目前为止,我看不到任何实时崩溃报告,也没有收到客户的投诉,它的工作正常。但是,如果您知道更好的方法,请告诉我。

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

用法

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