The One-Time Option: Single

In RxJava, a Single is a reactive type that is designed to deliver a single result, and that’s it. You either get that result or you get an error, such as when the data source cannot actually deliver you the result (e.g., IOException on a network call).

Single is a good type to use in a Room DAO when you are looking to just get the current query results, without keeping an open subscription for ongoing changes.

Item Singles

For cases where you are fairly certain that you will get a single row in your query results, you could use a Single for the desired entity or POJO type:

@Query("SELECT * FROM trips WHERE id=:id")
Single<Trip> singleTripById(String id);

However, in this case, if your query returns no rows, you will get an EmptyResultSetException from Room. When you subscribe() to the Single, you should provide both a listener for a POJO and an error listener, in case your query returns no rows.

List Singles

Another option is to have your DAO method return a Single for a List of entities or other POJOs:

@Query("SELECT * FROM trips ORDER BY title")
Single<List<Trip>> singleAllTrips();

This works for any number of rows, including the zero-row case (you just get an empty list).


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.