android - 如何在不破坏功能的情况下更改已弃用的房间交易
问题描述
所以 room 已弃用 beginTransaction/setTransactionSuccessful/endTransaction 并允许使用 runnables 和 callables 作为 runInTransaction() 函数的替代品。
但据我所知,我无法从可运行或可调用中获得返回值。在不更改功能的情况下修复代码并删除直接事务的方法是什么?
使用 Observable.fromCallable 有两个原因:在非 UI 线程上进行数据库调用,并在完成后获取返回值。
没有尝试任何其他方法,因为我不确定其他方法可能是什么。
Observable.fromCallable(//Observable.fromCallable allows to return value to subscriber
() -> {
long entryId = 0;
db.beginTransaction();
if (info.isChanged())
entryId = db.biDao().insert(info);
if (info.xChanged())
db.xDao().insert(info.getX());
db.setTransactionSuccessful();
db.endTransaction();
return entryId;//after insertion our id in to a model it should be updated since it's 0 initialized by default
})
//.subscribeOn(Schedulers.single())
.subscribeOn(Schedulers.io())
//because we can set model data only on main thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(//either way we close db eventually
entryId -> {
if (entryId > 0)
someModel.setId(entryId);
someModel.setDataChanged(false);
db.close();
},//done
throwable -> {//error
db.close();
throwable.printStackTrace();
}
);
我接受替代解决方案:1)删除弃用 2)在非 UI 线程中运行数据库查询 3)在 UI 线程中设置查询结果
我还尝试过更改部分代码,但使用“final long []”的方式看起来很丑/错误。有什么选择吗?
Observable.fromCallable(//Observable.fromCallable allows to return value to subscriber
() -> {
final long[] entryId = {0};
db.runInTransaction(new Runnable() {
@Override
public void run() {
if (info.isChanged())
entryId[0] = db.biDao().insert(info);
if (info.xChanged())
db.xDao().insert(info.getX());
}
});
return entryId[0];//after insertion our id in settingsModel should be updated since it's 0 initialized.
})
//.subscribeOn(Schedulers.single())
.subscribeOn(Schedulers.io())
//because we can set model data only on main thread
.observeOn(AndroidSchedulers.mainThread())
.subscribe(//either way we close db eventually
entryId -> {
if (entryId > 0)
someModel.setId(entryId);
someModel.setDataChanged(false);
db.close();
},//done
throwable -> {//error
db.close();
throwable.printStackTrace();
}
);
解决方案
推荐阅读
- python - 带有元组的 Line() 宏
- php - 如何使用 add_filter 获取带有 elementor (pro) 联系表单的参考代码?
- python - 我们可以在 python 中检测连接到 USB 集线器的设备吗
- r - 如何使用开始和结束来绑定许多 xlsx 文件
- node.js - 使用邮递员的请求正在工作,但使用浏览器它不起作用(nodejs)
- r - mle 错误:非有限差分值 [1]
- main - 我什么时候必须写 argc 和 argv?
- javascript - iPhone 上的 Safari 仅第一次运行“按类添加的 CSS 动画”
- sql - 使用 POSTGIS 生成 MVT 并排除不同缩放级别的一些几何图形
- sql - 如何将 2 个字符串列(日期和时间)转换为一个时间戳