【发布时间】:2018-02-09 21:17:29
【问题描述】:
我将 RxJava2 与 Room SQLite 一起使用。我的 DAO:
@Dao
public interface HeroDao {
@Insert
long create(Hero hero);
}
这就是我在 RxJava2 中使用它的方式:
Observable.just((int) heroDao.create(hero))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(id -> /** do stuff **/);
但是当我运行应用程序时,我在 Logcat 中得到的错误是 Cannot access database on the main thread since it may potentially lock the UI for a long period of time.我已经尝试将 .allowMainThreadQueries() 附加到数据库构建器并且插入通过,以便确认我的 observable 的正确性。看来 LiveData 和 AsyncTasks 是我可以尝试的其他方法,但是当我已经对 RxJava2 进行了大量投资时,我宁愿不去那里。
那么为什么我会收到这个错误? subscribeOn(Schedulers.io()) 不足以从主线程中卸载工作吗?否则我怎么做到这一点?似乎将 Room 查询转换为我遗漏的 observable 有一些微妙之处?
【问题讨论】:
标签: android rx-java2 android-room