RxJava: Nested Observers

Asked by At

I have a really tricky problem.

I have a method of void insert(User user) in my DAO. I wrapped it with :

public Completable insertUser(User user) {
    return Completable.fromAction(() -> userDao.insert(user))
            .subscribeOn(Schedulers.io())

which returns a Completable. In my ViewModel, I just return the same thing:

public Completable insertUser(User user) {
    return userDao.insertUser(user);

And in my UI, I observe on the completable :

    vm.insertUser(vm.getSomeUsers())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new CompletableObserver() {
                @Override
                public void onSubscribe(Disposable d) {
                    // Do nothing
                }

                @Override
                public void onComplete() {
                    userAdapter.populate( ? ) // here I need the refreshed user
                }

                @Override
                public void onError(Throwable e) {
                }
            });

The problem is that my insert does not return the updated user, I cannot change it to Observable<User> insertUser() because I'm using a lower version of Room.

So my question is, how can I populate the adapter with the updated user ? I have another method in my dao Flowable<User> getUsers(), but I have to use another observer to retrieve the users, so that leads to nested observers.

What is the best way to do it ?

1 Answers

0
Tuby On

You can do it as simple as

public Single<User> insertUser(User user) {
    return Completable.fromAction(() -> userDao.insert(user))
            .subscribeOn(Schedulers.io())
            .andThen(Single.just(user));

It will return user you just inserted.