Cancelling an Observable in RxJava

前端 未结 3 465
死守一世寂寞
死守一世寂寞 2021-01-18 20:24

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.

3条回答
  •  长情又很酷
    2021-01-18 21:05

    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.

提交回复
热议问题