Drop delete trigger for Room database - android

I am using room database to store comments and RxJava as a listener to do some stuff when the database is changed.
I want to not call the callback when delete is called on the table, only when insert is called.
What i found out so far is that Room library has triggers that are called on delete, insert and update of the table that in turn call RxJava's methods.
Is there any way to drop the delete trigger and get callbacks only for the insert and update methods?
Here is my CommentDAO:
#Query("SELECT * FROM comments" )
fun getAll(): Flowable<List<Comment>>
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(comment: Comment)
#Delete
fun delete(comment: Comment)
And my RxJava callback functions:
/**
* Inserts comment into comment database
*
* #param object that's going to be inserted to the database
*/
fun saveComment(comment: Comment) {
Observable.just(comment).subscribeOn(Schedulers.io()).map({ comment1 -> commentdb.commentDao().insert(comment1) }).subscribe()
}
/**
* Removes comment from the database
*
* #param comment object that's going to be removed
*/
fun removeComment(comment: Comment){
Observable.just(comment).subscribeOn(Schedulers.io()).map({ comment1 -> commentdb.commentDao().delete(comment1) }).subscribe()
}
fun createCommentObservable(uploader: CommentUploader) {
commentdb.commentDao().getAll().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
{
success -> uploader.queue(success)
}
)
}

You can get a Flowable<List<Comment>> that only emits on insertions and not on deletions by filtering the original getAll() Flowable so that only those List<Comment> items are passed through that contain more Comments than the previous List<Comment>.
You can implement this filtering with the following transformations:
Prepend the flowable with an empty list so that we have a baseline for insertions.
Get RxJava window()s of size 2, so that we will be able to compare adjacent items.
window() returns Flowable<Flowable<Comment>>. Convert it to Flowable<List<Comment>> with flatMap() and toList() on the inner Flowable.
Filter those 2-element windows that represent an insertion (the size of the first element is less than the size of the second).
Emit only the 2nd element of the filtered windows.
In Kotlin:
fun getAllAfterInsertions() {
getAll()
.startWith(emptyList<String>()) // (1)
.window(2, 1) // (2)
.flatMap({ w -> w.toList().toFlowable() }) // (3)
.filter({ w -> w.size == 2 && w[0].size < w[1].size }) // (4)
.map({ window -> window[1] }) // (5)
}

To delete without notification I simply replace
MyDao().delete()
with one executing a #Query
MyDao().deleteLast()
then thew Flowable doesn't emit a new event. The #Dao looks like this
#Dao
abstract class MyDao : BaseDao<Data> {
#Query("DELETE FROM Data WHERE id = (select min(id) from Data)") // or something else
abstract fun deleteLast()
#Delete
fun delete(data: Data)
}

Related

Unlike Livedata, using Flow in Room query doesn't trigger a refresh when updating a table entry but works if I delete or insert an entry

When using Livedata as a return type for a select* query on a table in Room, then I observe on it, I get triggers if I update/insert/delete an entry in that table. However, when I tried using Kotlin Flow, I only get 2 triggers.
The first trigger gives a null value as the initial value of the stateflow is a null. The second trigger is the list of entries in the Room table.
If I perform an insert/delete action on the DB, I receive a trigger from the StateFlow.
However, If I update an entry, the Stateflow doesn't trigger.
N.B: The update operation works correctly on the DB. I checked using DB inspector.
Data class & DAO
#Entity
data class CartItem (
#PrimaryKey
val itemId: Int,
var itemQuantity: Int=1
)
#Dao
interface CartDao {
#Query("SELECT * FROM CartItem")
fun getAllItems(): Flow<List<CartItem>>
#Update
suspend fun changeQuantityInCart(cartItem:CartItem)
#Insert
suspend fun insert(item: CartItem)
#Delete
suspend fun delete(cartItem:CartItem)
}
ViewModel
val cartItems: StateFlow<List<CartItem>?> =
repo.fetchCartItems().stateIn(viewModelScope, SharingStarted.Lazily, null)
Fragment
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.cartItems.collect {
Log.e("Update","Update")
}
My pitfall was that I was updating the object like this:
currentItem.itemQuantity = currentItem.itemQuantity + 1
changeQuantity(currentItem)
(currentItem is an object of class CartItem which is received initially from the getAllItems Flow in the DAO.)
(changeQuantity fun calls the changeQuantityInCart fun in the DAO.
This caused the reference of the CartItem object in the StateFlow to hold the updated value of the object with the new itemQuantity value before calling the update on the DB.
After that, when calling the Update fun in the DAO, the DB entry is updated and the Flow value changes, but when putting it in the Stateflow no changes are detected. Thus, the stateflow doesn't trigger as it is how stateflows differ from livedata.
In the case of livedata, it will trigger regardless if the new value is the same or not.
Thus, to solve this bug do not change the value of the object in the stateFlow before calling a DB update operation like this:
val updatedCartItem = cartItem.copy(itemQuantity = cartItem.itemQuantity + 1)
changeQuantity(updatedCartItem)

Kotlin Flow - Nullable value

Is it possible to check if Flow sends back a value and to act on it if it doesn't?
override suspend fun insertUserResponse(userResponse: UserResponse) {
val userResponseFromBDD: Flow<UserResponse>? = userResponseDAO.searchUserByToken(userResponse.profilePOJO.uniqueID)
userResponseFromBDD?.collect {
userResponseDAO.updateUser(userResponse)
} ?: {
userResponseDAO.insertUser(userResponse)
}
}
Several remarks:
There are two types of queries - one-shot and streams. For your use-case you need one-shot query (to ge response or null once with searchUserByToken and once - to insert or update value). For one-shot queries in Room you can use suspend function with no Flow:
#Query("SELECT * FROM userResponse where id = :id")
suspend fun searchUserByToken(id: Int):UserResponse?
And your code with checking value would be:
override suspend fun insertUserResponse(userResponse: UserResponse) {
val userResponseFromBDD = userResponseDAO.searchUserByToken(userResponse.profilePOJO.uniqueID)
userResponseFromBDD?.let { userResponseDAO.updateUser(userResponse)}
?: userResponseDAO.insertUser(userResponse)
}
With Flow you get stream, that issues values whenever data is updated in DB. That's why in your use-case you can get values in loop: you get value value from searchUserByToken -> you update value -> you get new value since Room uses Flow and invokes searchUserByToken again -> you update value -> ...
If you use Room's #Insert(onConflict = OnConflictStrategy.REPLACE) you can not to check if userResponse is in DB and use just insertUser method (since if user is in db insert would cause it's update)

Asynchronously iterate over all Room records only once

I would like to perform an asynchonous operation on each record in a large Room table.
I thought I could add a method returning Flow in my DAO like this:
#Query("SELECT * FROM events")
fun getEvents(): Flow<EventEntity>
But according to this blog post and this documentation page returning a Flow is making an "observable read" so the Flow never completes and it watches for database changes.
My goal is to iterate over all the entities only once. I don't want the "observability" behavior. Also, since the table is very large, I don't want to load all the records into a List at once in order to avoid consuming too much memory.
Could you recommend some solution, please?
Create a new method that does not use Flow.
#Query("SELECT id FROM events")
fun getAllIds(): List<Int> // If your primary key is Integer.
#Query("SELECT * FROM events WHERE id = :id")
fun getById(id: Int): EventEntity?
Use Kotlin coroutines to call this method on IO thread.
There could be several strategies to load one row at a time. This is the simplest - get all ids and load each item one at a time.
suspend fun getEvents() {
withContext(Dispatchers.IO) {
// Get entities from database on IO thread.
val ids = dao.getAllIds()
ids.forEach { id ->
val event = dao.getById(id)
}
}
}
Pagination based approach
This approach assumes that you have a column that stores timestamp (eg. created_at).
#Query("SELECT * from events WHERE created_at > :timestamp ORDER BY created_at LIMIT 10")
fun getAfter(timestamp: Long): List<EventEntity>
You can use this method to paginate.
suspend fun getEvents() {
withContext(Dispatchers.IO) {
var timestamp: Long = 0
while (true) {
// Get entities from database on IO thread.
val events = dao.getAfter(timestamp)
// Process this batch of events
// Get timestamp for pagination offset.
timestamp = events.maxBy { it.createAt }?.createAt ?: -1
if (timestamp == -1) {
// break the loop. This will be -1 only if the list of events are empty.
}
}
}
}

Access and Delete a row in one query in SQLite

I am using Room Database to make a database to store information in a table. I want to access one entry from the table and delete the same entry without the need to call two functions.
#Query("SELECT * FROM history_packet_table ORDER BY timestamp ASC LIMIT 1")
fun get(): HistoryPacket?
#Query("DELETE FROM history_packet_table ORDER BY timestamp ASC LIMIT 1")
fun delete()
I want these two operations to happen only by calling get. Is there a way?
I believe that you can add the following to the Dao :-
#Transaction
fun getAndDelete() {
get()
delete()
}
Obviously you can call the function what you wish. However, the get seems to be useless as it is.
So you may want something like :-
#Query("SELECT * FROM history_packet_table WHERE timestamp = (SELECT min(timestamp) FROM history_packet_table)")
fun get() :HistoryPacketTable
#Query("DELETE FROM history_packet_table WHERE timestamp = (SELECT min(timestamp) FROM history_packet_table)")
fun delete() :Int
#Transaction
fun getAndDelete() :HistoryPacketTable {
// Anything inside this method runs in a single transaction.
var rv: HistoryPacketTable = get()
val rowsDeleted: Int = delete()
if (rowsDeleted < 1) {
rv = HistoryPacketTable();
//....... set values of rv to indicate not deleted if needed
}
return rv
}
Note as LIMIT on delete is turned off by default, the queries can be as above, this assumes that timestamp is unique otherwise multiple rows may be deleted, in which case the Dao could be something like
:-
#Delete
fun delete(historyPacketTable: HistoryPacketTable) :Int
#Transaction
fun getAndDelete() :HistoryPacketTable {
// Anything inside this method runs in a single transaction.
var rv: HistoryPacketTable = get()
val rowsDeleted: Int = delete(rv)
if (rowsDeleted < 1) {
rv = HistoryPacketTable();
//....... set values to indicate not deleted
}
return rv
}

Using concat for requesting Data from DB and if it empty fetch from Service not working?

I need to request from local storage and if it's empty I should request to Service and store in DB ,but if the DB isn't empty I should ignore the second part.
I'm using Room persistence DB
( Flowable), I mean if I store in DB , I could listen to changes .
I'm using concat but neighter of the parts are working
val item1 = itemDao.loadItem(id)
val item2 = apiIcaSeResource
.fetchItem(offerId)
.toFlowable()
.doOnNext { item ->itemDao.saveItem(Item(...) }
Flowable.concat(item1, item2)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
// items ->
}, {
Timber.e(it, "Error reading items")
})
#Query("SELECT * FROM offer WHERE id = :offerId")
fun loadItem( offerId: String): Flowable<Item>
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveItem(items: Item)
#GET("item/{itemId}")
Single<Item> fetchItem(#Path("itemId") Long itemId);
#Query("SELECT * FROM offer WHERE id = :offerId")
fun loadItem( offerId: String): Flowable<Item>
With the Room DAO defined like this, if an item does not exist the Flowable will emit nothing. There will be no onNext events. Also defined as Flowable Room never emits onComplete.
Flowable.concat waits for the first Flowable to emit onComplete then subscribes to the second Flowable and emits all items.
Since alpha5 you can specify the return type in Room as Maybe<Item> so you can detect if there is an existing item in the db. Another option is to define the return type as Flowable<List<Item>> and Room will emit an empty list if the item does not exist in the DB.
If you switch Room to:
#Query("SELECT * FROM offer WHERE id = :offerId")
fun loadItem( offerId: String): Flowable<List<Item>>
you could do something like this (calls the API only if there are 0 items in the DB):
item1.flatMap { if(it.size == 0) item2 else Flowable.just(it) }
Note that this will end the stream if there is an error in the API call. Check the onErrorXXX operators to work around that.

Categories

Resources