首页 > 解决方案 > LiveData:AndroidX 重构后无法在后台线程上调用 observeForever

问题描述

重构为 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 重构)中中断。这是一个错误,有没有办法让它再次工作?

标签: androidandroid-architecture-componentsandroidxandroid-livedataandroid-architecture-paging

解决方案


看起来您对 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);
    }
};

并将其传递给分页库(假设您正在使用LiveData<PagedList>

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

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


推荐阅读