Search code examples
androidrx-javaandroid-roomrx-java2rx-android

Room Database - How to return entire row after insert?


I have query that inserts a row

@Dao
public interface NoteDao {
    @Insert
    Long insert(Note note);

}

I'm using RxJava to perform the query on the background thread:

 public void insert(Note note) {
        Single.fromCallable(() -> noteDao.insert(note))
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onSuccess(@NonNull Long aLong) {
                        Log.d(TAG, "onSuccess: New row Id: " + aLong);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }
                });

    }

Currently it successfully returns, the newly created primary key for the inserted DAO. How would I return the entire inserted row, WITHOUT performing a second query using the new row id?

In postgresql I would do something like this:

`INSERT INTO note_table(note_title, note_description) VALUES ($1, $2) RETURNING *`

Not sure how to do it with the Room library


Solution

  • As stated in the documents of Transcation, if you want to perform two queries in one shot you have to use transactions and there is no other option as far as I know for standard database operations

    check below as here we are doing you should do similar

     @Dao
     public interface NoteDao {
        @Insert
        Long insert(Note note);
    
        @@Query(“SELECT * FROM Note WHERE noteId = :id)
        Long getNote(id Long);
    
        @Transaction
        public void insertAndRetrieve(Note note):Note {
             // Anything inside this method runs in a single transaction.
    
             val id =  insert(note);
            return getNote(id);
         }
     }