Created
May 13, 2015 21:13
-
-
Save jamonholmgren/3a37a5d7695ac7e0bd9b to your computer and use it in GitHub Desktop.
RubyMotion async module that gives a pretty syntax.
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
class AppDelegate | |
include Async | |
def application(application, didFinishLaunchingWithOptions:launchOptions) | |
thread_1 = async do | |
i = 0 | |
300_000.times do | |
sleep 0.000001 | |
i += (300_000 - i) | |
end | |
main { puts i } | |
end | |
thread_2 = async do | |
i = 0 | |
900_000.times do | |
sleep 0.000001 | |
i += (900_000 - i) | |
end | |
main { puts i } | |
end | |
after thread_1, thread_2 do | |
puts "They're both done." | |
end | |
true | |
end | |
end | |
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
module Async | |
def async(&callback) | |
GroupAsync.new.async(&callback) | |
end | |
def main(&callback) | |
Dispatch::Queue.main.async(&callback) | |
end | |
def after(*asyncs, &callback) | |
async do | |
asyncs.each{|a| a.group.wait } | |
callback.call | |
end | |
end | |
class GroupAsync | |
attr_reader :group | |
def initialize | |
@group = Dispatch::Group.new | |
end | |
def async(&callback) | |
Dispatch::Queue.concurrent.async(group) do | |
callback.call | |
end | |
self | |
end | |
alias_method :and, :async | |
def then(&callback) | |
Dispatch::Queue.concurrent.async do | |
group.wait | |
callback.call | |
end | |
self | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment