How cancel network request in retrofit and rxjava

869 views Asked by At

I have a multiple buttons; When I press new button, previous(with another button) running request should be interrupted and new runs. How to realize it?

for (button : Buttons)  { 
button.setOnClickListener(b -> networkApi.getLongContentFromUrl(url)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<JsonElement>() {
                        @Override
                        public void onCompleted() {}

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(JsonElement jsonElement) {
                            //do with result
                        }
                    }));
    }
1

There are 1 answers

0
akarnokd On BEST ANSWER

You can have a common SerialSubscription and assign your subscriber to it on button click. It will unsubscribe and thus cancel your previous stream:

SerialSubscription serial = new SerialSubscription();
for (Button btn : buttons) {
    btn.setOnClickListener(e -> {
         Subscriber<JsonElement> s = new Subscriber<JsonElement>() {
             @Override
             public void onCompleted() {}
             @Override
             public void onError(Throwable e) {}
             @Override
             public void onNext(JsonElement jsonElement) {
                 //do with result
             }
         };
         serial.set(s);
         networkApi.getLongContentFromUrl(url)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    });
}