How to cancel multiple networking requests using Moya

I would just cancel the current provider session + tasks:

provider.manager.session.invalidateAndCancel()

The request method returns a Cancellable. From the documentation we can read:

The request() method returns a Cancellable, which has only one public function, cancel(), which you can use to cancel the request.

So according to this, I made a simple test and call:

var requests: [Cancellable] = []
@objc 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()
}

I set up a proxy using Charles and it seems to be working as expected. No request was sent - each request was cancelled.

So, the answer to your questions is:

  1. You can keep it in [Cancellable] array.
  2. Go through the array and cancel each request that you want to cancel.

EDIT

The main problem is that you adding the provider to the array and you try to map provider as Cancellable, so that cause the error. You should add reqest to the array. Below you can see the implementation.

let provider = MoyaProvider<SomeAPIService>()
let request = provider.request(.endPoint1(object: object)) { // block body }
Operator.shared.requests.append(request)
//Then you can cancell your all requests.