Last active
August 29, 2015 14:19
-
-
Save jmartinesp/30154ab8e922c73c0291 to your computer and use it in GitHub Desktop.
I just got real tired of dispatch_async...
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
// | |
// Async.swift | |
// | |
// Used as: Async().delay(2).onBackground({ ... }).onMainThread({ ... }).start() | |
// | |
// Created by Arasthel on 22/04/15. | |
// Copyright (c) 2015 Arasthel. All rights reserved. | |
// | |
import Foundation | |
class Async { | |
private var onBackgroundClosure : (() -> Void)? | |
private var onMainThreadClosure : (() -> Void)? | |
private var delay : Float = 0 | |
init() { | |
} | |
func onBackground(closure : (() -> Void)) -> Async { | |
onBackgroundClosure = closure | |
return self | |
} | |
func onMainThread(closure : (() -> Void)) -> Async { | |
onMainThreadClosure = closure | |
return self | |
} | |
func delay(seconds : Float) -> Async { | |
delay = seconds | |
return self | |
} | |
func start() { | |
if delay > 0 { | |
if onBackgroundClosure != nil { | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(self.delay) * Double(NSEC_PER_SEC))), | |
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), | |
{ | |
self.onBackgroundClosure!() | |
if self.onMainThreadClosure != nil { | |
dispatch_async(dispatch_get_main_queue(), self.onMainThreadClosure!) | |
} | |
}) | |
} else if onMainThreadClosure != nil { | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(self.delay) * Double(NSEC_PER_SEC))), | |
dispatch_get_main_queue(), onMainThreadClosure!) | |
} | |
} else { | |
if onBackgroundClosure != nil { | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), { | |
self.onBackgroundClosure!() | |
if self.onMainThreadClosure != nil { | |
dispatch_async(dispatch_get_main_queue(), self.onMainThreadClosure!) | |
} | |
}) | |
} else if onMainThreadClosure != nil { | |
dispatch_async(dispatch_get_main_queue(), self.onMainThreadClosure!) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment