LiveData:AndroidX重构后无法在后台线程上调用observeForever

时间:2018-10-11 20:25:24

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

通过AndroidStudio重构为androidx后,由于以下错误,我的分页库中的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重构)中中断。 这是一个错误,有没有办法使其再次正常工作?

1 个答案:

答案 0 :(得分:0)

好像您对AndroidX的重构将您更新到需要观察主线程的LiveData版本。如果您将LiveData更新为最新的Android之前版本1.1.1,就会看到此信息。

无法从UI线程中完成LiveData的观察,但是根据您的操作,可能会很好。如果您的DataSource实际上没有进行任何加载,则可以告诉Paging库使用包装UI / Main线程的执行程序:

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()方法)