How to do a single row query with Android Room

ⅰ亾dé卋堺 提交于 2021-02-17 21:31:10

问题


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.

I can have something like:

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

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!


回答1:


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

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 -> { ... });

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, you use this the same way as you use any other Single from RxJava. The details will vary based on your needs.



来源:https://stackoverflow.com/questions/49825789/how-to-do-a-single-row-query-with-android-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!