Created
May 17, 2016 12:46
-
-
Save juliengdt/0bbdfdcb69d511a56def62ac0a02b4f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Throttle { | |
static func onQueue(queue: NSOperationQueue, by timeInterval: NSTimeInterval, function: () -> ()) { | |
queue.cancelAllOperations() | |
let delayOperation = DelayOperation(timeInterval: timeInterval) | |
let throttledOperation = NSBlockOperation() { | |
function() | |
} | |
throttledOperation.addDependency(delayOperation) | |
queue.addOperations([delayOperation, throttledOperation], waitUntilFinished: false) | |
} | |
} | |
class DelayOperation: NSOperation { | |
private let timeInterval: NSTimeInterval | |
override var asynchronous: Bool { | |
get{ | |
return true | |
} | |
} | |
private var _executing: Bool = false | |
override var executing:Bool { | |
get { return _executing } | |
set { | |
willChangeValueForKey("isExecuting") | |
_executing = newValue | |
didChangeValueForKey("isExecuting") | |
if _cancelled == true { | |
self.finished = true | |
} | |
} | |
} | |
private var _finished: Bool = false | |
override var finished:Bool { | |
get { return _finished } | |
set { | |
willChangeValueForKey("isFinished") | |
_finished = newValue | |
didChangeValueForKey("isFinished") | |
} | |
} | |
private var _cancelled: Bool = false | |
override var cancelled: Bool { | |
get { return _cancelled } | |
set { | |
willChangeValueForKey("isCancelled") | |
_cancelled = newValue | |
didChangeValueForKey("isCancelled") | |
} | |
} | |
init(timeInterval: NSTimeInterval) { | |
self.timeInterval = timeInterval | |
} | |
override func start() { | |
super.start() | |
self.executing = true | |
} | |
override func main() { | |
if cancelled { | |
executing = false | |
finished = true | |
return | |
} | |
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(timeInterval * Double(NSEC_PER_SEC))) | |
dispatch_after(when, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { | |
self.finished = true | |
self.executing = false | |
} | |
} | |
override func cancel() { | |
super.cancel() | |
cancelled = true | |
if executing { | |
executing = false | |
finished = true | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Throttle.onQueue(queue, by: autocompleteThrottleInterval) { [weak self] in | |
self?.performAutocompleteSearch(searchString) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment