How to do a single row query with Android Room
Asked Answered
R

2

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!

Racoon answered 13/4, 2018 at 22:14 Comment(0)
S
22

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.

Selfdetermination answered 13/4, 2018 at 22:25 Comment(3)
Thanks! In the above example, User is not an observable right? then .subscribe() won't work right?Racoon
@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<User> edition of findByUserId(), which handles the background threading for you if you subscribe() on a background thread.Selfdetermination
or You can use Maybe and use switchIfEmptyOzmo
P
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

Process answered 7/12, 2022 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.