I have an observable that is performing a download. However I want to cancel that observable when I click on a button.
How is that possible?
Thank you.
This should give you the general idea. The summary is to use Observable.using() and subscribe to the Observable with a Subscriber so you can call subscriber.unsubscribe() when the user clicks the button to cancel.
Here's an outline.
Subscriber subscriber = ...;
Observable
// create a stream from a socket and dispose of socket
// appropriately
.using(socketCreator(host, port, quietTimeoutMs),
socketObservableFactory(charset),
socketDisposer(), true)
// cannot ask host to slow down so buffer on
// backpressure
.onBackpressureBuffer()
.subscriber(subscriber);
On clicking a button call:
subscriber.unsubscribe()
This will stop the observable stream and call socketDisposer() to stop the network activity.
You haven't specified what is the nature of your download (ftp, http, etc) but the answer doesn't really change because all of those transports will fit this pattern.