纤维素回调函数

4
当使用Celluloid时,我该如何在异步方法完成任务(回调)时得到通知?
示例代码:
  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

一旦 foo 内的工作完成,我希望能立即收到通知。

2个回答

1
我建议使用观察者模式。Celluloid通过通知支持此功能。请查看维基获取一些信息:https://github.com/celluloid/celluloid/wiki/Notifications 这里是一个可用的代码示例:
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

0

目前我认为新的条件功能是处理这个问题的首选方式。

Celluloid wiki page on Conditions上的示例太大了,无法在此处粘贴,但简单来说,您可以创建一个由调用方法发出信号的条件对象。调用者只需等待条件满足即可。


我认为TS询问了异步回调执行的问题,这与等待异步返回不同。 - zuba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接