How to cancel the Alamofire interface

Look at the following example

Static fileprivate var requestCacheArr = [DataRequest](); / / MARK: - a network request let dataRequest = our SessionManager. Default. The request (" "). The responseJSON {(responseJSON) in / / remove web request has been completed self.removeTask(task: responseJSON.request!) ; } / / record network request self. RequestCacheArr. Append (dataRequest); for task in self.requestCacheArr{ task.cancel(); } self.requestCacheArr.removeAll();Copy the code

How to cancel the interface request after Alamofire+Moya

var requests: [Cancellable] = [] func doRequests() { for i in 1... 20 { let request = provider.request(MyApi.someMethod) { result in print(result) } requests.append(request) } requests.forEach { cancellable in cancellable.cancel() } // here I go through the array and cancell each request. requests.removeAll() }Copy the code

Alamofire+Moya+Rxswift How to cancel a network request

Cancel all interface func cancelAllRequest () {apiProvider. Manager. Session. GetTasksWithCompletionHandler {(sessionDataTask, uploadData, downloadData) in sessionDataTask.forEach { $0.cancel() } uploadData.forEach { $0.cancel() } downloadData.forEach { Func cancelAllRequest(_ url: $0. Cancel ()}} String) { apiProvider.manager.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, DownloadData) in sessionDatatask.foreach {// Only cancel the request for the specified URL if ($0. OriginalRequest? .url? .absoluteString == url) { $0.cancel() } } } }Copy the code

After using Rxswift, another better control to cancel is the DisposeBag

DisposeBag, like the name, is a Bag type data structure that stores data of Disposable.

Every time you see Disposable call disposed(by: In fact, disposables are put into disposables for management. When disposeBag is disposed, disposables managed therein are disposed separately, but disposeBag cannot be called actively. Dispose can only be disposed automatically on deinit, so dispose can only be disposed by re-assigning disposeBag, as in:

disposeBag = DisposeBag()
Copy the code

So the life cycle of the interface is controlled by the disposeBag, which is defined in the controller, and when the controller is destroyed, all the interfaces in it are also cancelled