Peter Lapisu
Peter Lapisu

Reputation: 20965

Alamofire how to maintain request order?

i am using a single serial queue as the rootQueue / request / serialization queue

let queue = DispatchQueue(label: "APIManager.rootQueue")
a.session = Session(configuration: sessionConfiguration,
                    delegate: a,
                    rootQueue: queue,
                    startRequestsImmediately: true,
                    requestQueue: queue,
                    serializationQueue: queue,
                    interceptor: nil,
                    serverTrustManager: nil,
                    redirectHandler: nil,
                    cachedResponseHandler: nil,
                    eventMonitors: [])

however the requests seems to be completed in random order as to the order they were created

Compleations print to console:

[2][Request]: GET https://...
[1][Request]: GET https://...
[4][Request]: GET https://...
[3][Request]: GET https://...
[5][Request]: GET https://...

the number in [] represent the creation order PS: the order is also wrong during serialization

the queue is serial but the results looks like from concurrent

how to maintain a FIFO order of requests and results

Upvotes: 2

Views: 605

Answers (1)

Jon Shier
Jon Shier

Reputation: 12770

If you want to make requests in sequence rather than in parallel you can:

  1. Nest them. Start the next request inside the completion handler of the previous request.
  2. Wrap Alamofire requests in Operations and set dependencies between the operations such that they execute in the order you want.
  3. Use Alamofire's Combine integration to publish the first request's response, then flatMap in the next request.
  4. Use Swift's new concurrency feature to wrap Alamofire's completion handlers so you can use the async-await syntax. This will be supported by Alamofire directly in an upcoming release.

Ultimately, you probably want to reevaluate whether FIFO is what you really want, or whether you can build a system that doesn't care when requests complete. Such a system will likely be easier to manage, as you remove dependencies between requests, and higher performance, as you remove any waiting necessary to ensure the requests are in the right order.

Upvotes: 1

Related Questions