Skip to content

Instantly share code, notes, and snippets.

@jamonholmgren
Created May 13, 2015 21:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamonholmgren/3a37a5d7695ac7e0bd9b to your computer and use it in GitHub Desktop.
Save jamonholmgren/3a37a5d7695ac7e0bd9b to your computer and use it in GitHub Desktop.
RubyMotion async module that gives a pretty syntax.
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
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