Created
April 18, 2019 11:07
-
-
Save TiagoBras/3fea72326303edcb64413fde647fde0a 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 hidden or 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) | |
| } | |
| } | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: