Skip to content

Instantly share code, notes, and snippets.

@jmartinesp
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmartinesp/30154ab8e922c73c0291 to your computer and use it in GitHub Desktop.
Save jmartinesp/30154ab8e922c73c0291 to your computer and use it in GitHub Desktop.
I just got real tired of dispatch_async...
//
// 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