Ruby 赛璐珞回调
使用赛璐珞时,当异步方法完成其作业(回调)时,如何获得通知 示例代码:Ruby 赛璐珞回调,ruby,callback,celluloid,Ruby,Callback,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}, b
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内部的工作完成后尽快得到通知。我建议使用Observer模式。赛璐珞通过通知支持此功能。请查看wiki以了解一些信息: 下面是一个工作代码示例:
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
现在,我认为新的条件功能是处理这个问题的首选方法
来自的示例太大,无法粘贴到此处,但简单地说,您可以创建一个条件对象,一旦完成,该对象将由被调用的方法发出信号。调用方只需等待条件满足。谢谢Chuck,这正是我想要的。我想TS要求异步回调执行,这与等待异步返回不同