Cancel a timed event in Swift?

前端 未结 7 1935
说谎
说谎 2020-11-27 15:36

I want to run a block of code in 10 seconds from an event, but I want to be able to cancel it so that if something happens before those 10 seconds, the code won\'t run after

7条回答
  •  隐瞒了意图╮
    2020-11-27 16:14

    You need to do this:

    class WorkItem {
    
    private var pendingRequestWorkItem: DispatchWorkItem?
    
    func perform(after: TimeInterval, _ block: @escaping VoidBlock) {
        // Cancel the currently pending item
        pendingRequestWorkItem?.cancel()
    
        // Wrap our request in a work item
        let requestWorkItem = DispatchWorkItem(block: block)
    
        pendingRequestWorkItem = requestWorkItem
    
        DispatchQueue.main.asyncAfter(deadline: .now() + after, execute: 
        requestWorkItem)
    }
    }
    
    // to use
    
    lazy var workItem = WorkItem()
    
    private func onMapIdle() {
    
        workItem.perform(after: 1.0) {
    
           self.handlePOIListingSearch()
        }
    }
    

    References

    Link swiftbysundell

    Link git

提交回复
热议问题