RxJava and Room
In a previous chapter, we saw how a Room DAO could return a LiveData
object as a wrapper around the “real” data to be retrieved from the database. Then, the @Query
method would no longer be a blocking call, but instead would return the LiveData
immediately, with the actual query results being delivered to any observers of the LiveData
.
Not surprisingly, you can do the same thing with RxJava types. Simply wrap the return type from the @Query
method in a suitable RxJava type. You get the same results as you do with LiveData
: the @Query
method returns the RxJava object immediately, and you get the actual query results via RxJava’s subscriber system.
However, RxJava is a much richer library, and it is commensurately more complex. In this chapter, we will explore what RxJava types can be returned by a @Query
, how those work with respect to data changes, and how the underlying data type affects all of that.
Adding RxJava
RxJava has its own dependencies. In an Android app, typically you will use io.reactivex.rxjava2:rxjava
and io.reactivex.rxjava2:rxandroid
, where the latter provides utility classes like AndroidSchedulers
.
However, Room itself does not have a transitive dependency upon RxJava. Otherwise, everybody using Room would need to pull in RxJava, and that would add unnecessary bloat.
So, in addition to the regular dependencies for RxJava and the regular dependencies for Room (e.g., android.arch.persistence.room:runtime
), you also need the android.arch.persistence.room:rxjava2
dependency. This contains the glue code necessary to tie Room to RxJava:
implementation "android.arch.persistence.room:runtime:1.1.1"
implementation "android.arch.persistence.room:rxjava2:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
If you forget this dependency, but you have the regular RxJava and Room dependencies, you will not notice a problem right away. You will be able to use RxJava types in your DAO, because Android Studio knows about RxJava through your existing dependencies. However, when you go to build and run the project, your build will fail with:
Error:(41, 24) error: To use RxJava2 features, you must add `rxjava2` artifact from Room as a dependency. android.arch.persistence.room:rxjava2:<version>
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.