25

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!

rysv
  • 2,416
  • 7
  • 30
  • 48

2 Answers2

21

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.

majurageerthan
  • 2,169
  • 3
  • 17
  • 30
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks! In the above example, User is not an observable right? then .subscribe() won't work right? – rysv Apr 14 '18 at 00:46
  • 1
    @srvy: In the example after the first quoted passage, the return value is `User`, and you need to make that `findByUserId()` call on a background thread. In the example after the second quoted passage, I am using your `Single` edition of `findByUserId()`, which handles the background threading for you if you `subscribe()` on a background thread. – CommonsWare Apr 14 '18 at 01:06
  • or You can use Maybe and use switchIfEmpty – jknair0 Jun 30 '19 at 13:19
0

According to the Google docs: For single result queries, the return type can be any data object (also known as POJOs). For queries that return multiple values, you can use java.util.List or Array. Google docs

JeckOnly
  • 347
  • 2
  • 10