房间 - SELECT 查询、获取或默认
Room - SELECT query, get or default
在 SQL Brite 中,有一个方法 mapToOneOrDefault
。房间里有类似的东西吗?
为模特说
@Entity(tableName = "users")
data class User(@PrimaryKey val name: String)
与道
@Dao
interface UserDao {
@Query("SELECT FROM users where name = :name")
fun getUserByName(name: String): Flowable<User>
}
如果数据库中没有 John
,则 returns 对 getUserByName("John")
没有任何意义。有没有办法获得默认值,比如 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("")
没有默认机制。
您可以从 Flowable<User>
更改为 Flowable<List<User>>
。如果没有用户,您将得到一个空列表。您可以使用 map
检查和 return 默认值或 filter
+switchIfEmpty
。
或者您可以将 Flowable
更改为 Single
。使用 Single
,如果没有行匹配您的查询,将触发 onError
。然后,您可以将 onErrorReturn
或 onErrorResumeNext
实现为 return 默认值
在这种情况下,您可以使用 Maybe
而不是 Flowable
。
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.
如果查询没有 return 值,您可以使用运算符 defaultIfEmpty
映射到新对象。
在 SQL Brite 中,有一个方法 mapToOneOrDefault
。房间里有类似的东西吗?
为模特说
@Entity(tableName = "users")
data class User(@PrimaryKey val name: String)
与道
@Dao
interface UserDao {
@Query("SELECT FROM users where name = :name")
fun getUserByName(name: String): Flowable<User>
}
如果数据库中没有 John
,则 returns 对 getUserByName("John")
没有任何意义。有没有办法获得默认值,比如 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("")
没有默认机制。
您可以从 Flowable<User>
更改为 Flowable<List<User>>
。如果没有用户,您将得到一个空列表。您可以使用 map
检查和 return 默认值或 filter
+switchIfEmpty
。
或者您可以将 Flowable
更改为 Single
。使用 Single
,如果没有行匹配您的查询,将触发 onError
。然后,您可以将 onErrorReturn
或 onErrorResumeNext
实现为 return 默认值
在这种情况下,您可以使用 Maybe
而不是 Flowable
。
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.
如果查询没有 return 值,您可以使用运算符 defaultIfEmpty
映射到新对象。