AsyncRunner for Ruby/GLib
Was playing around a bit with a synchronous network library that I wanted to use from a GTK+ frontend. Obviously this wouldn’t work too well as the UI would be blocked while waiting for the library to return from it’s network calls. So I wanted to run the network operations in the background using a thread but still get the callbacks in the main thread to be able to update the UI from there.
I ended up writing a small class I called AsyncRunner which is a small proxy to call methods in a various thread and get the callback in the main thread. It’s using the GLib Mainloop so it would only be useful in the cases where you actually have one.
require 'thread-sync'
class MySyncClass
def foo_method(arg)
end
def bar_method(arg1, arg2)
end
end
sync = MySyncClass.new
# In order to get the methods of MySyncClass asynchronous it is wrapped in an AsyncRunner.
async = AsyncRunner.new(sync)
async.foo_method('test') do
ui_update()
end
main_loop = GLib::MainLoop.new
main_loop.run
Wouldn’t it be easier to use an asynchronous network library instead (with non-blocking sockets etc.)?
@oliver: Definitely in the case one exists. In this case I was using the Twitter4r library though and the alternative would be to write my own Twitter library (which would be more work).
i <3 ruby-gtk ruby-gnome examples
keep them coming
I dont even recall stuff like
GLib::MainLoop.new
being used ever before
@markus, thanks I will try
For someone new to GTK : In a regular GTK application you would use “Gtk::main” instead of creating your own mainloop like I did in the example above.
I use it to try out the AsyncRunner from the command line and also to create a simple example without involving any GTK .