-
-
Save seyhunak/14b5fa3ad54dfaeb727d5be9a21ff291 to your computer and use it in GitHub Desktop.
DispatchGroup convenience wrapper for executing a series of blocks concurrently
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
import Foundation | |
extension DispatchGroup { | |
/// Completes a series of blocks and finally executes a completion handler. | |
/// | |
/// - Parameters: | |
/// - label: An optional DispatchQueue label (defaults to bg) | |
/// - qos: An optional DipatchQos (defaults to background) | |
/// - blocks: The series of blocks to call. | |
/// - completion: The final completion handler when all blocks are | |
/// finished. | |
/// | |
/// Ensure you call the completion handler in every block. | |
func complete( | |
label: String = "bg", | |
qos: DispatchQoS = .background, | |
_ blocks: ((() -> Void) -> Void)..., | |
completion: @escaping () -> Void) { | |
for block in blocks { | |
self.enter() | |
DispatchQueue( | |
label: label, | |
qos: qos).async { | |
block({ | |
self.leave() | |
}) | |
} | |
} | |
self.notify(queue: .main) { | |
completion() | |
} | |
} | |
} | |
// MARK: - Example | |
DispatchGroup().complete( | |
{ completion in sleep(1); print("execution 1"); completion() }, | |
{ completion in print("execution 2"); completion() }, | |
{ completion in print("execution 3"); completion() } | |
) { | |
print("end of group completion handler") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment