Skip to content

Instantly share code, notes, and snippets.

@temoki
Last active January 26, 2018 15:25
Show Gist options
  • Save temoki/943b849d8f4e0c7bfddca3a7db1cab00 to your computer and use it in GitHub Desktop.
Save temoki/943b849d8f4e0c7bfddca3a7db1cab00 to your computer and use it in GitHub Desktop.
Execute `APIKit.Session.send(_:callbackQueue:handler:)` synchronously.
import APIKit
import Result
extension APIKit.Session {
class func sendSynchronous<Request>(_ request: Request) -> Result<Request.Response, APIKit.SessionTaskError> where Request: APIKit.Request {
return shared.sendSynchronous(request)
}
/// Execute `send(_:callbackQueue:handler:)` synchronously.
/// This method should be called on non-main thread.
func sendSynchronous<Request>(_ request: Request) -> Result<Request.Response, APIKit.SessionTaskError> where Request: APIKit.Request {
guard !Thread.isMainThread else { fatalError("'\(#function)' should be called on non-main thread.") }
var result: Result<Request.Response, SessionTaskError>? = nil
let semaphore = DispatchSemaphore(value: 0)
send(request) {
result = $0
semaphore.signal()
}
_ = semaphore.wait(timeout: .distantFuture)
return result!
}
}
DispatchQueue(label: "FooBar").async {
let fooResult = Session.sendSynchronous(FooRequest())
switch result {
case .success(let response):
print(response)
case .failure(let error):
print(error)
}
let barResult = Session.sendSynchronous(BarRequest())
switch result {
case .success(let response):
print(response)
case .failure(let error):
print(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment