Issue
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)
}
}
Solution
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 inRoom
you can use suspend function with noFlow
:
@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 invokessearchUserByToken
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 justinsertUser
method (since if user is in db insert would cause it's update)
Answered By - sergiy tikhonov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.