1

I want to send a request right after Room finished deleting or adding some item/items. To a database I use room + livedata, but for add/delete item I use doAsync. How I can get a callback when item deleting/adding is completed?

Examples for add/delete and get in my database

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveUser(user: SavedUserModel)

@Query("SELECT * FROM SavedUserModel")
fun getUser(): List<SavedUserModel>

@Query("DELETE FROM SavedShoppingListModel WHERE id LIKE :id")
fun deleteById(id: String)
Strangelove
  • 761
  • 1
  • 7
  • 29
  • "I use doAsync" -- what do you mean by this? Since you are in Kotlin, you could switch to coroutines and have these be `suspend` functions. With coroutines, you would no longer need a callback, as you find out when the work is done when those `suspend` functions return. – CommonsWare Oct 05 '19 at 12:22
  • @CommonsWare he just wants to check if the query executes till the end I guess. – coroutineDispatcher Oct 05 '19 at 12:29

1 Answers1

1

You can return an Int from delete or update. The value will be the number of affected rows. Once return is called by simple programing you know that execution of the method has finished. Check this thread for more, most voted answer.

Or, you can use Room + RxJava and return a Completable and look for the on completion state in the onComplete method. This one is sweeter solution IMO. But the first solution also would work, I guess.

I think that if you also return LiveData<List<T>> from the selection query, your delete would be able to be detected from room. Not really sure for this last one.

EDIT: As @CommonsWare mentioned in comments, you another option is coroutines. Mark methods as suspended and then go to paragraph 1 of this answer.

coroutineDispatcher
  • 7,718
  • 6
  • 30
  • 58