dxtr
dxtr

Reputation: 715

Replace AsyncTask with Rxjava for Room Database

I'm trying to replace AsyncTask with RxJava, since Async is deprecated in Android 11. however I cannnot get RxJava to work with Room,

This is currently working code with Asynctask:

In Repository:

public void insertItems(List<Items> items){
    new insertItemsAsyncTask(PrjDao).execute(items);
}

private static class insertItemAsyncTask extends AsyncTask<List<Items>, Void, Void>{
    private PrjDao prjDao;

    private insertItemAsyncTask(PrjDao prjDao){
        this.prjDao = prjDao;
    }

    @Override
    protected Void doInBackground(List<Items>... lists) {
        prjDao.insertItems(lists[0]);
        return null;
    }
}

in DAO

@Insert
void insertItems(List<Items> items);

I replaced repository code with:

public void insertItems(List<Items> items){
    Completable.fromAction(() -> prjDao.insertItems(items)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new CompletableObserver() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void onError(@NonNull Throwable e) {

                }
            });
}

However It is not working, even though I managed to get Log output in onComplete.

Upvotes: 0

Views: 546

Answers (1)

Dat Pham Tat
Dat Pham Tat

Reputation: 1463

Try:

DAO:

@Insert
Completable insertItems(List<Items> items);

Repository:

public void insertItems(List<Items> items){ 
    prjDao.insertItems(items))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(...);
}

Or better so:

Repository:

public Completable insertItems(List<Items> items){ 
    return prjDao.insertItems(items))
}

And then, subscribe to the completable and handle subscribe callbacks where you actually call insertItems().

insertItems(items)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

In my opinion, repository should only provide bridge to the DB interface, and the caller should be the one to handle the subscribe callbacks, as each caller may want to handle the callbacks differently.

UPDATE

To use rxjava with room, please check that you have all needed dependencies in your build.gradle file:

implementation "androidx.room:room-runtime:[roomVersion]"
implementation "androidx.room:room-rxjava2:[roomVersion]"
annotationProcessor "androidx.room:room-compiler:[roomVersion]"

I currently use roomVersion 2.2.5

Here is a simple working demo of room + rxjava I just created, maybe you will find differences there:

https://github.com/phamtdat/RxRoomDemo

Upvotes: 2

Related Questions