1

I have the following code:

Single<Item> update(...) {
...
return Single.create(subscriber -> aCall.execute(..) {
public void onResponse(..){
subscriber.onSuccess(..)
}
public void onError() {
  if(shouldReset) {
    subscriber.unsubscribe();
  } else {
    subscriber.onError();
  }
}
}));
    }

When calling the method:

update(..) 
.doOnSubscribe(counter++)
.doAfterTerminate(counter--)
.subscribe();

I've noticed that the counter is never decreased if subscriber.unsubscribe(); is called. Why is that?

If I change from doAfterTerminate() in doOnUnsubscribe(), the counter is decreased.

justmee
  • 355
  • 2
  • 14

1 Answers1

4

doAfterTerminate() will work in the case of termination due to an onError or an onComplete, but not unsubscription.

You can either use doFinally or combine doAfterTerminate() with doOnCancel to get the call also when unsubscribed.

Refer to this answer for an explanation of the difference.

elmorabea
  • 3,243
  • 1
  • 14
  • 20
  • and what if I m changing doAfterTerminate() into doOnUnsubscribe() ? Will doOnUnsubscribe() be called from onSuccess(), onError() and onUnsubsribe()? – justmee Mar 20 '18 at 09:33
  • Just a note that 1.x doesn't have `doFinally`. – akarnokd Mar 20 '18 at 09:43
  • I know that, that's my I m planning to change to doOnUnsubscribe(). Is doOnUnsubscribe() called after onError, onSuccess() and unsubscribe? – justmee Mar 20 '18 at 09:51
  • Yes, after a stream terminates (complete/error) an automatic unsubscription happens, it will also be called if you call unsubscribe yourself (programatically) – elmorabea Mar 20 '18 at 12:31