Created
November 2, 2012 01:00
-
-
Save mgartner/3997978 to your computer and use it in GitHub Desktop.
Busy wait vs asynchronous callback
This file contains hidden or 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
# 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 | |
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
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.