简体   繁体   中英

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.

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. 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

This works for me:

Let the insertStep(Step step); be like he following in your activitiesDao() :

@Insert
void insertStep(Step step);

And let be 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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