Skip to content

Instantly share code, notes, and snippets.

@sainecy
Last active October 10, 2023 03:08
Show Gist options
  • Save sainecy/4366a1b99c7317fac63bfeb19d1cfab2 to your computer and use it in GitHub Desktop.
Save sainecy/4366a1b99c7317fac63bfeb19d1cfab2 to your computer and use it in GitHub Desktop.
Run asynchronous blocks synchronous in swift. As Kotlin runBlocking. ONLY FOR TEST PURPOSES. Async code MUST BE RUNS ONLY ASYNCHRONOUSLY IN PRODUCTION!
import Foundation
private final class RunBlocking<T, Failure: Error> {
fileprivate var value: Result<T, Failure>? = nil
}
extension RunBlocking where Failure == Never {
func runBlocking(_ operation: @Sendable @escaping () async -> T) -> T {
Task {
let task = Task(operation: operation)
self.value = await task.result
}
DispatchQueue.global().sync {
while value == nil {
RunLoop.current.run(mode: .default, before: .distantFuture)
}
}
switch value {
case let .success(value):
return value
case .none:
fatalError("Run blocking not received value")
}
}
}
extension RunBlocking where Failure == Error {
func runBlocking(_ operation: @Sendable @escaping () async throws -> T) throws -> T {
Task {
let task = Task(operation: operation)
value = await task.result
}
DispatchQueue.global().sync {
while value == nil {
RunLoop.current.run(mode: .default, before: .distantFuture)
}
}
switch value {
case let .success(value):
return value
case let .failure(error):
throw error
case .none:
fatalError("Run blocking not received value")
}
}
}
func runBlocking<T>(@_implicitSelfCapture _ operation: @Sendable @escaping () async -> T) -> T {
RunBlocking().runBlocking(operation)
}
func runBlocking<T>(@_implicitSelfCapture _ operation: @Sendable @escaping () async throws -> T) throws -> T {
try RunBlocking().runBlocking(operation)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment