Search code examples
androidandroid-roomrx-java2

Why does this custom method of the DAO not work?


I ran across a problem when trying to insert an object into a sqlite database with the android room library.

I have the following dao:

@Dao
public abstract class ExerciseSetDao {
  public Completable insertExerciseSet(ExerciseSet set) {
    Completable completableSource = Completable.create(emitter -> {
      try {
        if(set.getRepRange() != null) {
          set.getRepRange().setOwnerExerciseSetId(set.getExerciseSetId());
        }

        _insertExerciseSet(set);

        emitter.onComplete();

      } catch (Exception e) {
        emitter.onError(e);
      }
    });

    return completableSource;
  }

  @Insert
  public abstract Completable _insertExerciseSet(ExerciseSet exerciseSet);
}

And in my view model I use it like this:

public void addExerciseSetButtonClick() {
  db.repRangeDao()
    .insertRepRange(repRangeForExerciseSet)
    .subscribeOn(Schedulers.newThread())
    .subscribe();

  exerciseSetToAdd.setRepRange(repRangeForExerciseSet);
  
  db.exerciseSetDao()
    .insertExerciseSet(exerciseSetToAdd)
    .subscribeOn(Schedulers.newThread())
    .subscribe();
}

Now the problem is when I check the database file I see that the repRangeForExerciseSet from the first command of the above method gets inserted perfectly fine but the exerciseSetToAdd doesn't get inserted into the database. BUT when i change the last line to the following (using the abstract method directly):

db.exerciseSetDao()
  ._insertExerciseSet(exerciseSetToAdd)
  .subscribeOn(Schedulers.newThread())
  .subscribe();

...the object gets added to the database too. But now my custom code in the insertExerciseSet() method doesn't get executed and I have no clue why it doesn't work the first way?

Thanks for your help.


Solution

  • Ok, I've found the problem.

    When I call the abstract method _insertExerciseSet(set); it doesn't get executed because the return type is a Completable. So I have two options to make it work.


    Calling the Completable with .subscribe(); like this _insertExerciseSet(set).subscribe();


    Or changing the return type for the abstract method _insertExerciseSet to void, because it already gets executed in an separate thread when it is called from the insertExerciseSet method.

      @Insert
      public abstract void _insertExerciseSet(ExerciseSet exerciseSet);