Search code examples
kotlinandroid-roomkotlinx.coroutines

How can I know @Insert of Room is completed?


My scenario

I use Coroutines and Room to save my app's user profile data. I have CompleteProfileActivity :in that User fill their information and confirm it( Confirm button ). I send them to server and observe response. If response is success. I save them to my ProfileDatabase.

My question How can I know my database is updated or my insertion is complete, my deletion is completed not by getting the size? @Insert @Delete is void return methods. So how can I know except the database size?

@Dao
interface ProfileDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveProfile(model:Profile)

@Query("SELECT * FROM profile_table")
fun getProfile():Deferred<Profile>
}

Solution

  • If the method call succeeded for insert, then it was succesful, otherwise you'd get an exception.

    Also, these don't have to be void-returning methods.

    You can have @Insert return the type of the primary key in the table, which will be the key of the newly inserted record.

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun saveProfile(model: Profile): Int
    

    In case of @Delete, it will return the number of rows deleted if you return an Int:

    @Delete
    fun deleteProfiles(profiles: List<Profile>): Int
    

    Same goes for a more manual implementation using @Query, returns the number of rows affected if you return an Int:

    @Query("DELETE FROM profiles")
    fun deleteAllProfiles(): Int