【问题标题】:LiveData: Cannot invoke observeForever on a background thread after AndroidX refactorLiveData:AndroidX 重构后无法在后台线程上调用 observeForever
【发布时间】:2018-10-11 20:25:24
【问题描述】:

在重构为 androidx(通过 AndroidStudio)后,我的分页库中的 PageKeyedDataSource 因此错误而中断:

 java.lang.IllegalStateException: Cannot invoke observeForever on a background thread

代码:

class TransactionDataSource(val uid: String, groupIdLiveData: LiveData<GroupNameIdPair>, var groupId: String) : PageKeyedDataSource<DocumentSnapshot, Transaction>() {
[...]
    init {
                val observer: Observer<GroupNameIdPair> = {
                    invalidate()
                    groupId = it.id

                }
                groupIdLiveData.observeNotNull(observer)
        }
[...]

由于 PageKeyedDataSource 默认在后台执行并且依赖于 LiveData,我想知道为什么这会在 LifeData 的 2.0.0 版(AndroidX 重构)中中断。 这是一个错误吗?有没有办法让它再次工作?

【问题讨论】:

    标签: android android-architecture-components androidx android-livedata android-architecture-paging


    【解决方案1】:

    看起来您对 AndroidX 的重构将您更新到了需要在主线程上观察的 LiveData 版本。如果您更新到 LiveData 的最新 pre-androidx 版本 1.1.1,您也会看到这一点。

    观察 LiveData 无法在 UI 线程外完成,但取决于您正在执行的操作,这可能没问题。如果您的 DataSource 实际上没有进行任何加载,您可以告诉 Paging 库使用包装 UI/主线程的执行器:

    static Executor MainExecutor = new Executor() {
        Handler handler = new Handler(Looper.getMainLooper());
        @Override
        public void execute(Runnable runnable) {
            handler.post(runnable);
        }
    };
    

    并将其传递给 Paging 库(假设您使用的是LiveData&lt;PagedList&gt;

    LivePagedListBuilder.create(myFactory, myConfig)
            //...
            .setFetchExecutor(MainExecutor)
            .build();
    

    (如果你使用的是 RxPagedListBuilder,还有一个类似的setFetchScheduler() 方法)

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多