加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 赛璐珞回调

发布时间:2020-12-17 02:05:04 所属栏目:百科 来源:网络整理
导读:当使用赛璐珞时异步方法完成它的工作(回调)时,如何收到通知? 示例代码: 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
当使用赛璐珞时异步方法完成它的工作(回调)时,如何收到通知?

示例代码:

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内部的工作完成后立即得到通知.

解决方法

我建议使用观察者模式.赛璐珞通过通知支持此功能.查看维基以获取一些信息: 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读