Getting insert id with RxJava (Room)

2019-08-22 09:34发布

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) {

            }
        });

Dao:

@Insert(onConflict = OnConflictStrategy.REPLACE)
    long insert(User user);

How can I get the row id after the DB operation?

1条回答
男人必须洒脱
2楼-- · 2019-08-22 10:33

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);

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) {
            }
        });
查看更多
登录 后发表回答