The Ongoing Option: Flowable

While we tend to focus on RxJava, bear in mind that RxJava 2 is itself based upon a broader Reactive Streams initiative, which has its own library. Effectively, Reactive Streams offers a common API for some high-level constructs, to help make it easier to have multiple disparate reactive libraries be able to inter-operate.

One key class from Reactive Streams is Publisher, which is the source of events that get “published”. The primary implementation of Publisher in RxJava 2 is Flowable. In principle, you could use either type with Room, though you may be more comfortable with Flowable, so you are sticking with native RxJava types.

Flowable is reminiscent of Observable, in that it represents a stream of ongoing events. If you use Flowable as the return type of your DAO method, not only will you get the initial query results, but so long as you are subscribed to that Flowable you will receive updated query results if Room thinks that the data may have changed.

Note that what Room thinks might have changed may not actually have changed. It is entirely possible that you will get the exact same data multiple times. Room is looking for SQL operations that modify the contents of a table; if your query does not happen to reference any of those modifications, the re-executed query will return the same data as you received in the previous results.

Item Flowables

If you have long-term interest in a single row, you could use a Flowable for a single entity or other POJO:

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

However, if your query returns no rows, the Flowable does not deliver anything to you. This may be OK in your situation, or it may not. If you need a positive indication that no rows matched your query, a Flowable for an individual object is not a good choice.

List Flowables

You could also have a Flowable for a List of entities or other POJOs:

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

In this case, you will always get a result, which may be an empty List if no rows matched your query.

Plus, since this is a Flowable, so long as you have an active subscriber, you will get updates delivered to you if Room thinks that the table(s) in your query may have been modified.


Prev Table of Contents Next

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