0

I am hitting first api which gives response in 60 seconds wherein second api needs to hit after stopping/cancelling first api request/response and get second api response immediately. But in my case, first api is cancelled and seconds api response not able to get.

I have even tried with Alamofire and default URLSession as well for the same.

1 Answers1

1

You can use DispatchWorkItem and perform debouncing, this will help cancel your first api if second needs to be hit.

private var pendingRequestWorkItem : DispatchWorkItem? // your work item

//function which calls your API being hit
func getData() {

  // cancels the first api or the the api currently being hit
  self.pendingRequestWorkItem?.cancel()
  
  let requestWorkItem = DispatchWorkItem { [weak self] in
    self?.getDataFromAPI()
  }
  self.pendingRequestWorkItem = requestWorkItem
  //this debounces for 0.5 secs, you can configure it as per your requirement(debouncing time you want)
  DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500), execute: requestWorkItem)
}


func getDataFromAPI() {
//your function which hits the API
}

Hope this helps.

Vyom Saraf
  • 11
  • 3