Reputation: 337
Below is the example code of RxAlamofire network request. My problem is that I want to cancel this request whenever the View Controller is dismissed.
I tried to assign this request to a global variable but requestJSON
method returns Observable<(HTTPURLResponse, Any)>
type.
Is there a way to handle this request when the View Controller is dismissed?
RxAlamofire.requestJSON(.get, sourceStringURL)
.debug()
.subscribe(onNext: { [weak self] (r, json) in
if let dict = json as? [String: AnyObject] {
let valDict = dict["rates"] as! Dictionary<String, AnyObject>
if let conversionRate = valDict["USD"] as? Float {
self?.toTextField.text = formatter
.string(from: NSNumber(value: conversionRate * fromValue))
}
}
}, onError: { [weak self] (error) in
self?.displayError(error as NSError)
})
.disposed(by: disposeBag)
Upvotes: 0
Views: 1793
Reputation: 489
As Valérian points out, when your ViewController is dismissed, it and all its properties will be deallocated (if retain count drops to 0 that is).
In particular, when disposeBag
property is deallocated, dispose()
will be called on all observable sequences added to this bag. Which, in turn, will call request.cancel()
in RxAlamofire implementation.
If you need to cancel your request earlier, you can try nil'ing your disposeBag
directly.
Upvotes: 0
Reputation: 1118
If you look at RxAlamofire's code: https://github.com/RxSwiftCommunity/RxAlamofire/blob/8a4856ddd77910950aa2b0f9e237e0209580503c/Sources/RxAlamofire.swift#L434
You'll see that the request is cancelled when the subscription is disposed.
So as long as your view controller is released (and its dispose bag with it!) when you dismiss it then the request will be cancelled if it hasn't finished of course.
Upvotes: 3