-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add DispatchOnce extension for DispatchQueue.
- Loading branch information
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
// | ||
// DispatchOnce.swift | ||
// FoundationX | ||
// | ||
// Created by Guanghui Liang on 2024/2/25. | ||
// Copyright © 2024 Guanghui Liang. All rights reserved. | ||
// | ||
|
||
import Foundation | ||
|
||
public extension DispatchQueue { | ||
|
||
private static var _onceTracker = [String]() | ||
|
||
/// Swift's DispatchOnce implementation. It's Thread safe. | ||
/// - Parameters: | ||
/// - token: A unique string. | ||
/// - block: Block to execute once | ||
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() | ||
} | ||
} |