Question

How can I get notified when an async method has finished it's job (callback) when using Celluloid?

Sample code:

  require 'celluloid/autostart'

  class Test
    include Celluloid

    def initialize(aaa)
      @aaa = aaa
    end

    def foo
      sleep 20
      @bbb = 'asdasd'
    end

    def bar
      "aaa is: #{@aaa}, bbb is: #{@bbb}"
    end
  end
  x = Test.new 111
  x.async.foo

I would like to get notified as soon as the job inside foo is done.

Was it helpful?

Solution

I recommend using the Observer pattern. Celluloid supports this via Notifications. Take a look at the wiki for some information: https://github.com/celluloid/celluloid/wiki/Notifications

Here's a working code example:

require 'rubygems'
require 'celluloid/autostart'

class Test
  include Celluloid
  include Celluloid::Notifications

  def initialize(aaa)
    @aaa = aaa
  end

  def foo
    sleep 2
    @bbb = 'asdasd'
    publish "done!", "Slept for 2 seconds and set @bbb = #{@bbb}"
  end

  def bar
    "aaa is: #{@aaa}, bbb is: #{@bbb}"
  end
end

class Observer
  include Celluloid
  include Celluloid::Notifications

  def initialize
    subscribe "done!", :on_completion
  end

  def on_completion(*args)
    puts "finished, returned #{args.inspect}"
  end
end


y = Observer.new
x = Test.new 111
x.async.foo

sleep 3

OTHER TIPS

Right now I think the new Conditions feature is the preferred way to handle this.

The example from the Celluloid wiki page on Conditions is too large to paste here, but simply put you can create a Condition object that is signalled by the called method once it is done. The caller can simply wait until the condition is met.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top