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)
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.