Why does this custom method of the DAO not work? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why does this custom method of the DAO not work? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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);
We are here to answer your question about Why does this custom method of the DAO not work? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji