使用RxJava获取插入ID(Room) [英] Getting insert id with RxJava (Room)
本文介绍了使用RxJava获取插入ID(Room)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用RxJava在下面添加一行,
I can add a row using RxJava with the following,
Completable.fromAction(() -> db.userDao().insert(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
});
道:
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
在执行数据库操作后如何获取行ID?
How can I get the row id after the DB operation?
推荐答案
如果要将RxJava与Room一起使用,可以更改insert
函数以返回包装Long
的RxJava Single,例如:
If you want to use RxJava with Room you can change the insert
function to return RxJava Single wrapping a Long
, like:
@Insert
Single<Long> insert(User user);
这样,您可以只订阅此Single
,并且会得到如下所示的ID作为Long:
This way you can just subscribe to this Single
and you'll get the id as Long with something like this:
db.userDao().insert(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Long>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(Long aLong) {
// aLong is the id
}
@Override
public void onError(Throwable e) {
}
});
这篇关于使用RxJava获取插入ID(Room)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文