0

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?

INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73

1 Answers1

1

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) {
            }
        });
gpunto
  • 2,573
  • 1
  • 14
  • 17
  • Could you please tell me the 'import' you use for the Single? I am having troubles as you can see here: https://stackoverflow.com/questions/67063811/error-when-returning-singlelong-using-room-insert-method?noredirect=1#comment118541314_67063811 – mantc_sdr Apr 12 '21 at 18:48