Reputation: 8482
In SQL Brite, there's a method mapToOneOrDefault
. Is there a similar thing in Room?
Say for Model
@Entity(tableName = "users")
data class User(@PrimaryKey val name: String)
and Dao
@Dao
interface UserDao {
@Query("SELECT FROM users where name = :name")
fun getUserByName(name: String): Flowable<User>
}
Not the stream returns nothing for getUserByName("John")
if there's no John
in DataBase. Is there a way to get a default value, say User("")
?
Upvotes: 2
Views: 2849
Reputation: 157457
Not the stream returns nothing for getUserByName("John") if there's no John in DataBase. Is there a way to get a default value, say User("")
There is no default mechanism.
You could change from Flowable<User>
to Flowable<List<User>>
. In case of no user you will get an empty list back. You can use a map
to check and return a default value or filter
+switchIfEmpty
.
Or you could change from Flowable
to Single
. With Single
, in case of no rows, matching your query, onError
will be triggered. You can then implement onErrorReturn
or onErrorResumeNext
to return a default value
Upvotes: 4
Reputation: 2835
You can use Maybe
instead of the Flowable
in this case.
Maybe: Conceptually, it is a union of Single and Completable providing the means to capture an emission pattern where there could be 0 or 1 item or an error signaled by some reactive source.
You can then use the operator defaultIfEmpty
to map to a new object if the query didn't return a value.
Upvotes: 0