Created
June 2, 2020 05:58
-
-
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
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 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