简体   繁体   中英

How to fetch data from room using RxJava

I am using MVVM architecture pattern to create an app.I am using RxJava wrapper to fetch data from room database rather than LiveData.I have set up my
DAO class and all necessary methods to carry out an operation.I want to know how can I fetch data using Flowable or Observable operator in repository.

Below is my code:

UserDao.java

@Dao
public interface UserDao {

@Insert
void insert(User user);

@Query("SELECT * FROM Users ORDER BY id DESC")
Flowable<List<User>> getAllUsers();

}

UserRepository.java

public class UserRepository {

private UserDb userDb;
private UserDao userDao;
private Flowable<List<User>> allUsers;
private Context ctx;

public UserRepository(Application application) {

    userDb = UserDb.getInstance(application);
    userDao = userDb.userDao();
    allUsers = userDao.getAllUsers();
    ctx = application.getApplicationContext();
}

public void insert(final User user){

   Completable.fromAction(() -> userDb.userDao().insert(user))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new CompletableObserver() {

                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onComplete() {

                                      Toast.makeText(ctx,"Data inserted", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onError(Throwable e) {


Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT).show();
                                    }
                                });

      }


 }

MainActivityViewModel.java

public class MainActivityViewModel extends AndroidViewModel {

private UserRepository repos;

public MainActivityViewModel(@NonNull Application application) {
    super(application);

    repos = new UserRepository(application);
 }

}    

Someone please let me know how can I fetch data using RxJava. Any help would be appreciated.

THANKS

you have to use

belows depen

    //RX Room
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';



  DatabaseClient.getInstance(view.getViewActivity())
            .getAppDatabase()
            .courseDao()
            .getCourseWhoHaveMaxDate(cr_id)
            .subscribeOn(Schedulers.newThread())
            .observeOn(Schedulers.newThread())
            .subscribe(new Consumer<CourseTable>() {
                @Override
                public void accept(CourseTable maxCourse) {

                }
            });

First, you can use the rxjava2 room adapter adding this line on your build.gradle:

implementation 'androidx.room:room-rxjava2:2.2.0-alpha01'

Second, i recommend you to use the rxjava2 adapter for room and edit your dao for:

@Dao
public interface UserDao {

@Insert
Completable insert(User user);

@Query("SELECT * FROM Users ORDER BY id DESC")
Flowable<List<User>> getAllUsers();

}

Ok, you can get directly the completable from dao and propagate this completable for your repository structure.

For the automatically fetch, this flowable observes the changes of your room db, if you insert a user, this flowable emits the new list which is the result of this query. The first time what you subscribe the flowable, this emits the list of users of this query, and for each user inserted, the flowable emits the new list of users.

Well, for use this flowable you can propagate this flowable through your repository structure and subscribe in your ViewModel like that:

repository.getFlowableAllUsers()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(userList -> { /* do anything with the fetched user list */ });

I highly recommend you to use a CompositeDisposable to dispose your subscriptions when the Component owner of the ViewModel dispose the execution, you can create a attribute of class that save this CompositeDisposable and finish it when the component ends his life.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM