Last active
March 30, 2018 14:13
-
-
Save eleev/8abcba47320a0d5b3183465180743572 to your computer and use it in GitHub Desktop.
DispatchOnce + Swift 3 (and above).swift
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
public extension DispatchQueue { | |
// MARK: - Properties | |
private static var _onceTracker = [String]() | |
// MARK: - Methods | |
/// Executes a block of code, associated with a unique token, only once. The code is thread safe and will onle execute the code once even in the presence of multithreaded calls. | |
/// | |
/// - Parameters: | |
/// - token: is a unique reverse DNS-style name such as io.eleev.astemir or a GUID | |
/// - block: is a non-escaping closure that is executed only once | |
public class func once(token: String, block: ()->Void) { | |
objc_sync_enter(self); defer { objc_sync_exit(self) } | |
if _onceTracker.contains(token) { | |
return | |
} | |
_onceTracker.append(token) | |
block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment