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
}
1条答案
按热度按时间webghufk1#
您可以使用DispatchWorkItem并执行去抖动,这将有助于在需要命中第二个API时取消第一个API。
希望这个有用。