Reputation: 12685
i am inserting and deleting a row in room database using following methods of ViewModel class
fun insert(rules: TableRules) = viewModelScope.launch {
repository.insert(rules)
}
fun delete(id: Int) = viewModelScope.launch {
repository.delete(id)
}
and retriving the data using this this method of DAO class
@Query("SELECT * FROM rules_table")
fun getAlphabetizedRules(): List<TableRules>
but i am not getting update data. i.e when i add one row and then retrive, i will not get newly added row. i close my app, remove from recent app list, start app again then retrive, then i will get that row.
same thing happens in case of delete also.
what i am missing i above.
Upvotes: 2
Views: 803
Reputation: 481
Mark the DAO method with @RawQuery annotation instead of normal @Query.
Upvotes: 0
Reputation: 93541
Launching a coroutine queues up work that will complete in the future. If you launch a coroutine and then immediately check the state of the table without waiting for the coroutine to finish, you have a race condition and will likely get the earlier state returned.
You need to call getAlphabetizedRules()
from inside the same coroutine that you launch to call insert()
or delete()
so it is happening after the database change.
Or alternatively, you can create a new coroutine or suspend function that join
s the returned Job from your existing insert()
and delete()
functions. For example:
suspend fun deleteAndGetUpdatedList(id: Int): List<TableRules> {
delete(id).join()
return repository.getAlphabetizedRules()
}
By the way, in your DAO, getAlphabetizedRules()
should be marked as a suspend
function to make it easier to use properly (not having to use withContext(Dispatchers.IO) { }
every time you call it.
Upvotes: 1