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

LiveData:在AndroidX重构后,无法在后台线程上调用ObserveForver,android,android-architecture-components,androidx,android-livedata,android-architecture-paging,Android,Android Architecture Components,Androidx,Android Livedata,Android Architecture Paging,重构到androidx(通过AndroidStudio)后,分页库中的我的PageKeyedDataSource因以下错误而中断: java.lang.IllegalStateException: Cannot invoke observeForever on a background thread 代码: class TransactionDataSource(val-uid:String,groupIdLiveData:LiveData,var-groupId:String):PageK

重构到androidx(通过AndroidStudio)后,分页库中的我的PageKeyedDataSource因以下错误而中断:

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

class TransactionDataSource(val-uid:String,groupIdLiveData:LiveData,var-groupId:String):PageKeyedDataSource(){
[...]
初始化{
val观察员:观察员={
使无效
groupId=it.id
}
groupIdLiveData.ObserveNotFull(观察者)
}
[...]

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

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

观察LiveData不能在UI线程外完成,但这取决于您正在执行的操作。如果您的数据源实际上没有进行任何加载,您可以告诉分页库使用一个包装UI/主线程的执行器:

static Executor MainExecutor = new Executor() {
    Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void execute(Runnable runnable) {
        handler.post(runnable);
    }
};
并将其传递到分页库(假设您使用的是
LiveData


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

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

观察LiveData不能在UI线程外完成,但这取决于您正在执行的操作。如果您的数据源实际上没有进行任何加载,您可以告诉分页库使用一个包装UI/主线程的执行器:

static Executor MainExecutor = new Executor() {
    Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void execute(Runnable runnable) {
        handler.post(runnable);
    }
};
并将其传递到分页库(假设您使用的是
LiveData

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

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