我需要在appwidgetprovider中观察一些liveData(在onUpdate期间).我想知道,以下哪一个更适合使用lifeCycleObserver?
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; }}
或者,我应该使用ProcesslifecycleOwner.get()吗?
两者都很好.但是,哪一个更合适?
解决方法:
最后,我坚持以下解决方案.它工作正常,因为我没有看到任何实时崩溃报告,或接收客户的抱怨.但是,如果您知道更好的方法,请告诉我.
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));}
总结 以上是内存溢出为你收集整理的android – 这是用于在AppWidgetProvider中观察LiveData的正确LifeCycleOwner全部内容,希望文章能够帮你解决android – 这是用于在AppWidgetProvider中观察LiveData的正确LifeCycleOwner所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)