简体   繁体   English

如何使用RxJava从房间获取数据

[英]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 我正在使用MVVM架构模式创建应用程序,正在使用RxJava包装器从房间数据库而不是LiveData中获取数据。
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. DAO类和执行操作的所有必要方法。我想知道如何使用存储库中的Flowable或Observable运算符获取数据。

Below is my code: 下面是我的代码:

UserDao.java 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 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 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. 有人请让我知道如何使用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: 首先,您可以使用rxjava2房间适配器在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: 其次,我建议您使用rxjava2适配器腾出空间并编辑dao:

@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. 好的,您可以直接从dao获取可完成对象,并将其传播给您的存储库结构。

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. 对于自动获取,此flowable观察您的房间db的变化,如果您插入用户,则此flowable会发出新列表,该列表是此查询的结果。 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. 首次订阅flowable时,它将发出此查询的用户列表,并且对于插入的每个用户,flowable都会发出新的用户列表。

Well, for use this flowable you can propagate this flowable through your repository structure and subscribe in your ViewModel like that: 好吧,要使用此可流动对象,您可以在存储库结构中传播该可流动对象,并在ViewModel中进行订阅,如下所示:

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. 我强烈建议您在ViewModel的组件所有者处理执行时使用CompositeDisposable来处理您的订阅,您可以创建一个类的属性来保存此CompositeDisposable并在组件寿命结束时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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