I want to cancel the previous request using RxAlamofire.
But I don't know where to call the cancel function.
I have a searchBar, and I call the API in function "textdidchange".
So, I want to cancel the previous request and call the API with new parameters.
Have any suggestion to help me?
Thanks.
func request(_ method: Alamofire.HTTPMethod, url:String, params:[String:Any] = [:], callback: @escaping (JSON) -> Void) {
var headers:[String:String] = [String:String]()
if token.isEmpty == false {
headers["Authorization"] = "Bearer \(token)"
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = 10.0
_ = SessionManager(configuration: configuration)
.rx.responseJSON(method,
url,
parameters: params,
encoding: ((method == .get) ? URLEncoding.default : JSONEncoding.default),
headers: headers)
.subscribeOn(SerialDispatchQueueScheduler.init(qos: .background))
.subscribe(onNext: { (r, data) in
let json = JSON(data)
if json["status"].stringValue == "success" {
callback(json["responseData"])
}else {
callback(json)
}
}, onError: { (error) in
callback(JSON(error))
})
.addDisposableTo(ResfulAPIDisposeBag)
}
We would need to add some delay, that will fire up the request after X seconds after the typing, but only if the phrase didn’t change.