如何使用Android Room执行单行查询 [英] How to do a single row query with Android Room

查看:160
本文介绍了如何使用Android Room执行单行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用带有RxJava的Android Room进行单行查询?我能够查询项目列表,没有问题.在这里,我想查找是否存在特定行.根据文档,看来我可以返回Single并检查是否存在EmptyResultSetException异常(如果不存在任何行).

How do I make a single row query with Android Room with RxJava? I am able to query for List of items, no issues. Here, I want to find if a specific row exists. According to the docs, looks like I can return Single and check for EmptyResultSetException exception if no row exists.

我可以有类似的东西:

@Query("SELECT * FROM Users WHERE userId = :id LIMIT 1")
Single<User> findByUserId(String userId);

如何使用此通话?看起来好像有一些onError/onSuccess,但是无法在Single<>上找到那些方法.

How do I use this call? Looks like there is some onError / onSuccess but cannot find those methods on Single<>.

usersDao.findByUserId("xxx").???

任何可行的例子都很棒!

Any working example will be great!

推荐答案

根据文档,看起来我可以返回Single并检查是否存在EmptyResultSetException异常(如果不存在任何行).

According to the docs, looks like I can return Single and check for EmptyResultSetException exception if no row exists.

或者,如果您通过其他方式处理后台线程,则只需返回 User .

Or, just return User, if you are handling your background threading by some other means.

@Query("SELECT * FROM Users WHERE userId = :id")
User findByUserId(String id);

如何使用此通话?

How do I use this call?

usersDao.findByUserId("xxx")
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(user -> { ... }, error -> { ... });

在这里,我展示了 subscribe(),其中包含两个lambda表达式,分别用于 User 和错误.您可以使用两个 Consumer 对象.我还假设您具有 rxandroid 作为 AndroidSchedulers.mainThread()的依赖项,并且希望将 User 交付给您线程.

Here, I show subscribe() taking two lambda expressions, for the User and the error. You could use two Consumer objects instead. I also assume that you have rxandroid as a dependency, for AndroidSchedulers.mainThread(), and that you want the User delivered to you on that thread.

IOW,您使用的方法与使用RxJava中任何其他 Single 的方法相同.详细信息将根据您的需求而变化.

IOW, you use this the same way as you use any other Single from RxJava. The details will vary based on your needs.

这篇关于如何使用Android Room执行单行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆