2

I am quite new to Rx java observables so I am not sure when to unsubscribe. this is how my code implementation is

Observable<String> sampleObservable = Observable.just(accountNum);
        Subscription sampleSub = sampleObservable.subscribeOn(Schedulers.io()).subscribe(new Action1<String>() {
            @Override
            public void call(String accountNum) {

                try {
                    //call backend api
                    AccountResponse response = getAccountDetails(accountNum);
                    logger.debug("Account response :" + response.toString());

                } catch (Exception e) {
                    logger.error(e.getMessage());

                }

            }

        });

Can I unsubscribe at the end "sampleSub.unsubscribe()". The concern that I have here is if "getAccountDetails(accountNum)" call takes time to complete and the code unsubscribes then will it cancel/affect the "getAccountDetails(accountNum)" call? If yes, then is there a way to unsubscribe only when that call is over?

Observable<String> sampleObservable = Observable.just(accountNum);
    Subscription sampleSub = sampleObservable.subscribeOn(Schedulers.io()).subscribe(new Action1<String>() {
        @Override
        public void call(String accountNum) {

            try {
                //call backend api
                AccountResponse response = getAccountDetails(accountNum);
                logger.debug("Account response :" + response.toString());

            } catch (Exception e) {
                logger.error(e.getMessage());

            }

        }

    });

   //unsubscribing
    sampleSub.unsubscribe();
akarnokd
  • 69,132
  • 14
  • 157
  • 192
Jack
  • 67
  • 1
  • 6

2 Answers2

1

you can dispose, In Rx api chain you will get fun called doOnSubscribe(disposable), store that disposable and call disposable.dispose() which will clear the subscription

Or

whenever you subscribe to stream will give you Disposable as a return, use that and dispose it.

(either way you can do that)

0

As documentation said

unsubscribe() Stops the receipt of notifications on the Subscriber that was registered when this Subscription was received.

It means that you can call this method if you don't need receive data anymore. You cat stop receiving data before the end of the sequense. For example, you can observe data from server, when you are on screen, but when you are closing screen, you can unsubscribe from this source.

karenkov_id
  • 630
  • 5
  • 8