从上一篇Room & RxJava 的使用引申而来的代码实际操作。
1. 定义一个数据库接口
复制代码
1
2
3
4
5
6
7
8
9
@Dao
public interface UserDao {
@Query("select * from user")
Flowable<List<UserEntity>> getUsers();
@Query("select * from user limit 1")
Flowable<UserEntity> getUser();
}
2. 查询数据库
复制代码
1
2
3
4
5
// ViewModel/DataRepository类:
public Flowable<List<UserEntity>> getUsers(){
return database.userDao().getUsers();
}
database为AppDatabase
类,继承RoomDatabase
。详见BasicSample中的AppDatabase类。
3. 在UI中引用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
// Activity 或 Fragment类:
userViewModel.getUsers()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<UserEntity>>() {
@Override
public void accept(List<UserEntity> entities) throws Exception {
adapter.setList(entities);
}
})
;
最后
以上就是谨慎台灯最近收集整理的关于RxJava 2 与 Room 查询实操的全部内容,更多相关RxJava内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复