RxJava with Room
We are going to implement RxJava with Room, Yes, RxJava with Room to achieve abstraction(Doing all work in the background, No need to worry). We will cover this topic in the easiest way.
Till now, we are using a room database with Live data for asynchronous(Multiple requests and Automatic fetching data when any changes) yes, Whenever any changes in the database table the UI should be updated automatically with updated data.
To integrate RxJava with Room need to add the below dependency in the project.
1 2 3 4 |
// 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” |
Why we use RxJava if Live data is doing all work?
We need to set up a background thread like in Kotlin coroutine or ThreadPool Executer to do the request work (Query in the database) fetching data then update UI.
So RxJava is better in handling this type of request as he did with Retrofit. If you have not checked RxJava with Retrofit you should learn first – https://mobikul.com/handle-api-call-using-rxjava2-retrofit2-android/
Let’s discuss important topics in the RxJava with Room.
1. Completable
2. Single
3. Maybe
4. Flowable
Completable – If you use it with @insert, @update, or @delete query then it will be called the onCompleted method in the success case of insertion, update, or deletion data from your table respectively.
For example –
1 2 |
@Insert Completable insert(User user); |
Single<Long> or Single<List<Long>> or Maybe<Long> or Maybe<List<Long>> – If you use it with @insert, @update, or @delete query then it will be called the success method(RxJava observable callback method) in the success case with effected table rows id.
For example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Insert <strong>Single</strong><Long> insert(User[] user); // or @Insert <strong>Single</strong><List<Long>> insert(User[] user); @Insert <strong>Maybe</strong><Long> insert(User user); //or @Insert <strong>Maybe</strong><List<Long>> insert(User[] user); |
Maybe – It is not syncing with the database at runtime, which means once you will get the updated data when you queried but it will not fetch automatically data from the database if anything changes happened in the database.
1 2 |
@Query(“SELECT * FROM Users WHERE id = :userId”) Maybe<User> getUserById(String userId); |
Flowable – It is syncing with the database at runtime, which means whenever any changes updated in the database then it will be fetched and updated on UI. The result will receive in onNext().
1 2 |
@Query(“SELECT * FROM Users WHERE id = :userId”) Flowable<User> getUserById(String userId); |