How do I insert data with Room and RxJava?
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
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()
})
}
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(...);