Skip to content

Commit

Permalink
feat: Add DispatchOnce extension for DispatchQueue.
Browse files Browse the repository at this point in the history
  • Loading branch information
Lguanghui committed Feb 25, 2024
1 parent 0f716e0 commit 51b8ba4
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Sources/FoundationX/Extensions/DispatchOnce.swift
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()
}
}

0 comments on commit 51b8ba4

Please sign in to comment.