Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 825
JoSem Avatar asked Dec 05 '17 11:12

JoSem


People also ask

How do you use a RxJava room?

Insert. The Room integration with RxJava allows the following corresponding return types for insert: Completable — where onComplete is called as soon as the insertion was done. Single<Long> or Maybe<Long> — where the value emitted on onSuccess is the row id of the item inserted.

What is Completable RxJava?

Completable is only concerned with execution completion whether the task has reach to completion or some error has occurred. interface CompletableObserver<T> { void onSubscribe(Disposable d); void onComplete(); void onError(Throwable error);

What is Room persistence library?

The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. Latest Update.


1 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(...);
like image 136
Mateusz Biedron Avatar answered Sep 19 '22 13:09

Mateusz Biedron