vadymmarkov / Malibu

:surfer: Malibu is a networking library built on promises

Home Page:https://vadymmarkov.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cancelAllRequests not working?

kevinrenskers opened this issue · comments

Super simpel test.

import Malibu

enum Endpoint: RequestConvertible {
  case fetchUsers

  static let baseUrl: URLStringConvertible? = "https://jsonplaceholder.typicode.com/"

  static var headers: [String : String] {
    return ["Accept" : "application/json"]
  }

  var request: Request {
    switch self {
    case .fetchUsers:
      return Request.get("users")
    }
  }
}

class ViewController: UIViewController {
  let networking = Networking<Endpoint>()

  override func viewDidLoad() {
    super.viewDidLoad()

    let promise = networking.request(.fetchUsers)

    promise.validate().done({ data in
      print("Success")
    }).fail({ error in
      print(error)
    })

    promise.cancel()
  }
}

With the method above, where I cancel a single network promise, the request is not made and neither the success or an error is printed. Great!

However, when I change that last line to networking.cancelAllRequests(), I do get "Success" printed out, and I can confirm that the request is indeed made.

Also, when I look at the code, I image that if the cancelling did work, the .fail handler would be called with a network error, right? Because it doesn't go through the Promise cancellation logic which suppresses the error by default.

Basically in the ResponseHandler.handle method this sort of check would need to be added I think:

if let error = error as? URLError, error.code == .cancelled {
  networkPromise.cancel()
  return
}

Update on the cancelAllRequests problem I am seeing: because self.queue.addOperation(operation) is itself done within an async operation (namely the middlewarePromise), by the time cancelAllRequests is executed, the queue is still empty. Only after cancelAllRequests is run on the empty queue, is the operation actually added to the queue. This seems like a problem to me :)

Added some logging within cancelAllRequests and execute..

cancelAllRequests - number of operations: 0
addOperation - number of operations: 1

I think you're right about cancelAllRequests being called when the queue is still empty. I'm not sure how to fix it in a good way though. One option could be to store network promises in array and then iterate through it and cancel in cancelAllRequests function.