android - 如何使用 Room 和 RxJava 插入数据?

标签 android database

db.activitiesDao().insertStep(step);

这将返回臭名昭著的错误:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

我是 RxJava 的新手,不想使用 AsyncTask。

最佳答案

尝试这样的事情。

Observable.fromCallable(() -> db.activitiesDao().insertStep(step))
        .subscribeOn(Schedulers.io())
        .subscribe(...);

或者如果有 void return 你可以这样做:

Completable.fromRunnable(new Runnable(){
        db.activitiesDao().insertStep(step)
    })
    .subscribeOn(Schedulers.io())
    .subscribe(...);

关于android - 如何使用 Room 和 RxJava 插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652371/

相关文章:

mysql - MYSQL 5.7 中的 native JSON 支持 : what are the pros and cons of JSON data type in MYSQL?

java - log4j spring jdbc异常

android - 我们如何在启用调试的 Android 6.0 设备上更轻松地切换 MTP?

android - 首先在 child 的 parent 上调用 removeView()

android 使 LinearLayout 及其子元素透明

android - 为 Google Cast 注册应用程序

ios - Sqlite_prepare_v2返回SQLite_ERROR

mysql - 尝试删除表 MySQL 中的字段内容后出错

android - 如何清除 android marshmallow 中的浏览历史记录

ruby-on-rails - Postgres 重复错误