gpt4 book ai didi

ruby - 赛璐珞回调

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:00 24 4
gpt4 key购买 nike

在使用 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 中的工作完成后立即得到通知。

最佳答案

我推荐使用观察者模式。 Celluloid 通过通知支持这一点。查看 wiki 以获取一些信息: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

关于ruby - 赛璐珞回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com