Reputation: 7456
Currently, I'm trying to streamline background thread to main thread executions in my application.
The way I'm doing that is this:
import Foundation
infix operator ~> {}
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
func ~> (backgroundClosure: () -> (), mainClosure: () -> ()) {
dispatch_async(queue) {
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), mainClosure)
}
}
which would let me do something like:
{ println("executed in background thread") } ~> { println("executed in main thread") }
Now... I wanted to extend this functionality to potentially be able to dispatch_after
to the main thread, so maybe I want it to be called 0.25 seconds later or something.
Is there a way to achieve this by passing in a parameter somehow?
Ideally, I'd be able to implement something like backgroundClosure ~>(0.25) mainClosure
, but I doubt that is possible
Upvotes: 1
Views: 145
Reputation: 5302
Just a suggestion:
infix operator ~> {}
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
func ~> (backgroundClosure: () -> (), secondParam: (delayTime:Double, mainClosure: () -> () )) {
// you can use the `delayTime` here
dispatch_async(queue) {
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), secondParam.mainClosure)
}
}
How to use:
{ print("executed in background thread") } ~> (0.25, { print("executed in main thread") })
Upvotes: 2
Reputation: 54
try this:
private let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
infix operator ~>{ associativity left precedence 140}
func ~> (backgroundClosure: ()->() , mainClosure: ()->()) {
dispatch_async(queue) { () -> Void in
backgroundClosure()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
mainClosure()
})
}}
Upvotes: 0