Kotlin Flow - Nullable value

2.6k views Asked by At

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)
    }
}
1

There are 1 answers

1
sergiy tikhonov On BEST ANSWER

Several remarks:

  1. 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)
}
  1. 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 -> ...

  2. 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)