如何使用Rxjava正确预填充数据库
这是我的岛
@Query("SELECT * from questions WHERE difficulty = :difficulty")
Flowable<List<Question>> getQuestions(String difficulty);
// Emits the number of users added to the database.
@Insert
public Maybe<long[]> insertQuestions(List<Question> questions);
这是我的数据库类
public static synchronized QuestionDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(), QuestionDatabase.class, "questions_database")
.fallbackToDestructiveMigration()
//.addMigrations(MIGRATION_1_2)
.addCallback(roomCallback)
.build();
}
return instance;
}
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
QuestionDao questionDao = instance.questionDao();
List<Question> questions = new ArrayList<>();
questions.add(new Question("A is correct", "A", "B", "C", 1, GameConstants.DIFFICULTY_EASY));
questions.add(new Question("C is correct", "A", "B", "C", 3, GameConstants.DIFFICULTY_HARD));
questions.add(new Question("B is correct", "A", "B", "C", 2, GameConstants.DIFFICULTY_EASY));
//inserting records
questionDao.insertQuestions(questions)
.subscribeOn(Schedulers.io())
//.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new Consumer<long[]>() {
@Override
public void accept(long[] longs) throws Exception {
}
},
new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
});
}
};
我遇到的问题如下:
仅当我在活动p.Ex上调用方法时才填充数据库:>
//getting flowable to subscribe consumer that will access the data from Room database. questionDao.getQuestions(GameConstants.DIFFICULTY_HARD) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Consumer<List<Question>>() { @Override public void accept(List<Question> questions) throws Exception { questionList = (ArrayList<Question>)questions; questionCountTotal = questionList.size(); Collections.shuffle(questionList); showNextQuestion(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { } } );
当我调用此方法时,我会得到两次询问。我通过在QuestionDao.getQuestions的accept方法中放置一个断点来进行检查。我相信有两个线程正在运行,其中一个正在填充,另一个正在运行以获取问题。
为什么会发生这种情况,我该如何正确实施呢?
提前感谢
如何使用Rxjava正确地预填充数据库,这是我的dao @Query(“ SELECT * from where where where困难=:difficulty”)Flowable > getQuestions(String ...
我相信以下更改将起作用