简体   繁体   English

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

[英]How do I insert data with Room and RxJava?

db.activitiesDao().insertStep(step);

This returns the infamous error:这将返回臭名昭著的错误:

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

I am kind new to RxJava and don't want to use AsyncTask.我是 RxJava 的新手,不想使用 AsyncTask。

Try something like this.尝试这样的事情。

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

Or if there is void return you can do:或者如果有无效回报,你可以这样做:

Completable.fromRunnable(new Runnable(){
        db.activitiesDao().insertStep(step)
    })
    .subscribeOn(Schedulers.io())
    .subscribe(...);
fun insertIntoDb(blog: Blog) {
    Observable.fromCallable {
        Runnable {
            appDb.blogDao().insert(blog)
        }.run()
    }
            .subscribeOn(Schedulers.io())
            .subscribe {
                D.showSnackMsg(context as Activity, R.string.book_mark_msg)
            }
}

See the above function.见上面的函数。 (Kotlin). (科特林)。 Must run the runnable.必须运行runnable。 Otherwise it won't save the data.否则它不会保存数据。 I have tested it with room.我已经用房间测试过了。 Happy coding快乐编码

or use below code,或使用以下代码,

@SuppressLint("CheckResult")
fun insertIntoDb(blog: Blog) {
    Completable.fromAction {
        appDb.blogDao().insert(blog)
    }.subscribeOn(Schedulers.io())
            .subscribe({
                Lg.d(TAG, "Blog Db: list insertion was successful")
            }, {
                Lg.d(TAG, "Blog Db: list insertion wasn't successful")
                it.printStackTrace()
            })
}
 fun insertContactUsData(
            contactUsData: ContactUsData,
            database: AppDatabase?,
            apiName: String
        ) {
            Observable.fromCallable {
                database?.contactUsDao()?.insertContactUs(contactUsData)
            }
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                      Lg.d(TAG, list inserted successfully")
                }
        }

Runnable is not required to insert data in a table Runnable 不需要在表中插入数据

This works for me:这对我有用:

Let the insertStep(Step step);insertStep(Step step); be like he following in your activitiesDao() :就像他在您的activitiesDao()

@Insert
void insertStep(Step step);

And let be addStep(Step step);并让是addStep(Step step); where you wish to insert the step:您希望插入步骤的位置:

 public void  addStep(Step step){
    Observable<Step> observable;
    observable = io.reactivex.Observable.just( step);
    observable.subscribeOn( Schedulers.io() )
            .subscribe( new Observer<Step>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull Step step) {
                    //Insert here
                    db.activitiesDao().insertStep(step);

                }

                @Override
                public void onError(@NonNull Throwable e) {
                       Log.e("Error", "Error at" + e);
                }

                @Override
                public void onComplete() {

                }
            } );
}

PS: I'm using rxjava2 PS:我正在使用 rxjava2

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

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