3

I am trying to understand what is the best way to handle a particular case, using RxJava.

I need to return an Observable which handles the removal of an account from the Android AccountManager. Unfortunately, this action is asynchronous and it needs a callback to handle the result.

Because of this, I am using the Observable.create method, in this way:

return Observable.create(subscriber -> {
        final Account account = getAccountIfExist();
        if (account == null) {
            subscriber.onError(new NoUserFoundException());
            return;
        }

        accountManager.removeAccount(account, future -> {
            boolean result = false;
            try {
                result = future.getResult();
            } catch (Exception ex) {
                Log.e(TAG, "Remove account not successful : ", ex);
                subscriber.onError(ex);
                return;
            }

            if (result) {
                subscriber.onNext(account.name);
                subscriber.onCompleted();
            } else {
                subscriber.onError(new RuntimeException("Cannot remove the account."));
            }
        }, null);
    });

But, Observable.create has different problems dealing backpressure and cancellation, as stated in this post

So, the question is, how can I use Observable.fromCallable (or an equivalent method) for handling callbacks (in general) and also dealing with backpressure and cancellation?

Community
  • 1
  • 1
Daniele Vitali
  • 3,848
  • 8
  • 48
  • 71

1 Answers1

1

You can try to use

Observable.defer

return Observable.defer(() -> {
    final Account account = getAccountIfExist();
        if (account == null) {
            return Observable.error(new NoUserFoundException());
        }
 accountManager.removeAccount(account, future -> {
            boolean result = false;
            try {
                result = future.getResult();
            } catch (Exception ex) {
                 return Observable.error(ex);
            }

            if (result) {
                Observable.just(account.name);
            } else {
                return Observable.error(new NoUserFoundException("Cannot remove the account."))
            }
        }, null);
});