Room and RxJava — easily linked together (Source)

Room 🔗 RxJava



Insert

@Insert
Completable insert(User user);// or
@Insert
Maybe<Long> insert(User user);// or
@Insert
Single<Long> insert(User[] user);// or
@Insert
Maybe<List<Long>> insert(User[] user);// or
@Insert
Single<List<Long>> insert(User[] user);

Update/Delete

@Update
Completable update(User user);// or
@Update
Single<Integer> update(User user);// or
@Update
Single<Integer> updateAll(User[] user);// or
@Delete
Single<Integer> deleteAll(User[] user);// or
@Delete
Single<Integer> deleteAll(User[] user);

Query

@Query(“SELECT * FROM Users WHERE id = :userId”)
User getUserById(String userId);
// RxJava support for Room
implementation “android.arch.persistence.room:rxjava2:1.0.0-alpha5”// Testing support
androidTestImplementation “android.arch.core:core-testing:1.0.0-alpha5”

Maybe

@Query(“SELECT * FROM Users WHERE id = :userId”)
Maybe<User> getUserById(String userId);

Single

@Query(“SELECT * FROM Users WHERE id = :userId”)
Single<User> getUserById(String userId);

Flowable/Observable

@Query(“SELECT * FROM Users WHERE id = :userId”)
Flowable<User> getUserById(String userId);

Testing

@RunWith(AndroidJUnit4.class)
public class UserDaoTest {
…
private UsersDatabase mDatabase;@Before
public void initDb() throws Exception {
    mDatabase = Room.inMemoryDatabaseBuilder(
                     InstrumentationRegistry.getContext(),
                     UsersDatabase.class)
            // allowing main thread queries, just for testing
            .allowMainThreadQueries()
            .build();
}

@After
public void closeDb() throws Exception {
    mDatabase.close();
}
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = 
                                      new InstantTaskExecutorRule();
@Test
public void insertAndGetUserById() {
    // Given that we have a user in the data source
    mDatabase.userDao().insertUser(USER);    // When subscribing to the emissions of user
    mDatabase.userDao()
             .getUserById(USER.getId())
             .test()
             // assertValue asserts that there was only one emission
             .assertValue(new Predicate<User>() {
                @Override
                public boolean test(User user) throws Exception {
                    // The emitted user is the expected one
                    return user.getId().equals(USER.getId()) &&
                      user.getUserName().equals(USER.getUserName());
                }
            });
}

Android Developers

The official Android Developers publication on Medium

Florina Muntenescu

Written by

Android Developer Advocate @Google

Android Developers

The official Android Developers publication on Medium