I would need to calculate the duration of each API request after we receive the response. It would be easy to do:
func performRequest(request: URLRequest) {
let startDate = Date()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
let duration = Date().timeIntervalSince(date: startDate)
}
}
The problem here is that when we do multiple requests at the same time - we might end up in a situation when the first request is calculating the duration while the next request already entered the performRequest method and changed the startDate. This will lead in incorrect duration calculation.
I am curious to know how can we make sure that all the requests and duration calculations are concurrent and thread-safe? And that the duration is calculated properly for each of the simultaneous requests without ending up in weird states.
Thank you!