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?