Skip to content

Instantly share code, notes, and snippets.

@mgartner
Created November 2, 2012 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgartner/3997978 to your computer and use it in GitHub Desktop.
Save mgartner/3997978 to your computer and use it in GitHub Desktop.
Busy wait vs asynchronous callback
# I think the only way to do what you want is to use some sort of busy-wait.
# However, I think it would be better for your ModelHelper to use callbacks instead.
class ModelHelper
# Using busy-wait.
def self.find_other_thing_by_id_busy(id)
other_thing = nil
make_async_request(id) do |response|
other_thing = OtherThing.new(response)
end
while other_thing.nil?
end
return other_thing
end
# Using a callback.
def self.find_other_thing_by_id_with_callback(id, &block)
make_async_request(id) do |response|
block.call(OtherThing.new(response))
end
end
end
# Using the busy-wait method:
other_thing = ModelHelper.find_other_thing_by_id_busy(id)
other_thing.profit()
# Using the callback method:
ModelHelper.find_other_thing_by_id_with_callback(id) do |other_thing|
other_thing.profit()
end
@matthewsinclair
Copy link

I'm not sure that the busy version works. When I tried this, the lines at [13..14] just cause the app to lock up and the thread from make_async_request [9..11] never gets a chance to run. At least, that appears to be the situation in the RubyMotion simulator, which is where I'm trying to get this to work.

@matthewsinclair
Copy link

Another change worth noting: sharing local variables between the BW::HTTP.get thread and the mainline is paved with danger. However, if you put the shared vars into a class (essentially a struct) and share that, then RubyMotion stops core dumping and seems to work fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment