Home » Android » android – How do I insert data with Room and RxJava?

android – How do I insert data with Room and RxJava?

Posted by: admin June 15, 2020 Leave a comment

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

How to&Answers:

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(...);

Answer:

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()
            })
}