Skip to content

Instantly share code, notes, and snippets.

@AlexandrGraschenkov
Created May 21, 2021 09:25
Show Gist options
  • Save AlexandrGraschenkov/60d661bdbf224c49f3c8cabfad2a39c5 to your computer and use it in GitHub Desktop.
Save AlexandrGraschenkov/60d661bdbf224c49f3c8cabfad2a39c5 to your computer and use it in GitHub Desktop.
Helpers for easy control on witch queue run your code
extension DispatchQueue {
static var background: DispatchQueue { return DispatchQueue.global(qos: .background) }
}
public typealias Cancelable = ()->()
func performInMain(mode: CFRunLoopMode = CFRunLoopMode.commonModes, closure: @escaping ()->()) {
if Thread.isMainThread && mode == .commonModes {
closure()
} else {
CFRunLoopPerformBlock(CFRunLoopGetMain(), mode.rawValue, closure)
}
}
func performInBackground(closure: @escaping ()->()) {
if Thread.isMainThread {
DispatchQueue.global(qos: .background).async(execute: closure)
} else {
closure()
}
}
func delay(_ delay: Double,
queue: DispatchQueue = DispatchQueue.main,
closure:@escaping ()->()) {
queue.asyncAfter(deadline: .now() + delay, execute: closure)
}
fileprivate var _privateKeys = Set<String>()
func once(file: String = #file, line: Int = #line, col: Int = #column, _ code: ()->()) {
let key = "\(file)|\(line)|\(col)"
objc_sync_enter(DispatchQueue.main);
defer { objc_sync_exit(DispatchQueue.main) }
if _privateKeys.contains(key) {
return
}
_privateKeys.insert(key)
code()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment