android - 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 重构)中中断。这是一个错误,有没有办法让它再次工作?
解决方案
看起来您对 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()
方法)
推荐阅读
- javascript - Typescript 接口定义动态
- php - 借助“帮助”功能创建键 => 值数组
- mysql - mysql将每行数据的最后N个字符移动到下一行
- c# - 即使更改代码,Visual Studio 似乎也会引发错误
- java - MM/dd/yyyy 日期格式给出的日期不正确
- amazon-s3 - 如何将文件从 s3 复制到 s3 同一个文件夹?
- c# - 找不到 ClipperOffset 类 C#
- kubernetes - 使用 kube-proxy ipvs 时的 Nodeport SFTP / SSH 连接超时
- react-native - Expo Build,自动更新我在应用商店和 Playstore 上的实时应用
- html - 美丽的汤 - find_all 函数返回页面中仅返回 20 个项目。实际结果在250左右