Skip to content

Instantly share code, notes, and snippets.

@seyhunak
Created June 2, 2020 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seyhunak/17c5549c6b5a67f950ce09a9e8a2ee02 to your computer and use it in GitHub Desktop.
Save seyhunak/17c5549c6b5a67f950ce09a9e8a2ee02 to your computer and use it in GitHub Desktop.
DispatchQueue extension for situations where one needs to run an expensive operation in background and then use its result in the main thread
import Foundation
extension DispatchQueue {
func asyncConsumeInMainQueue<T>(
work: @escaping () throws -> T,
mainSuccess: @escaping (T) -> Void,
mainError: @escaping (Error) -> Void) {
async {
do {
let result = try work()
DispatchQueue.main.async {
mainSuccess(result)
}
} catch {
DispatchQueue.main.async {
mainError(error)
}
}
}
}
func asyncConsumeInMainQueue<T>(
delay: TimeInterval,
work: @escaping () throws -> T,
mainSuccess: @escaping (T) -> Void,
mainError: @escaping (Error) -> Void) {
asyncAfter(deadline: .now() + delay) {
do {
let result = try work()
DispatchQueue.main.async {
mainSuccess(result)
}
} catch {
DispatchQueue.main.async {
mainError(error)
}
}
}
}
}
DispatchQueue.global(qos: .background).asyncConsumeInMainQueue(work: { () -> UIImage in
return try fetchImage(url: "https://example.com/image.jpeg")
}, mainSuccess: { [weak self] (image) in
self?.imageView.image = image
}) { (error) in
handleError(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment