class EventMachine::Channel
Provides a simple thread-safe way to transfer data between (typically) long running tasks in {EventMachine.defer} and event loop thread.
@example
channel = EventMachine::Channel.new sid = channel.subscribe { |msg| p [:got, msg] } channel.push('hello world') channel.unsubscribe(sid)
Public Class Methods
Public Instance Methods
Source
# File lib/em/channel.rb, line 21 def num_subscribers return @subs.size end
Return the number of current subscribers.
Source
# File lib/em/channel.rb, line 53 def pop(*a, &b) EM.schedule { name = subscribe do |*args| unsubscribe(name) EM::Callback(*a, &b).call(*args) end } end
Fetches one message from the channel.
Source
# File lib/em/channel.rb, line 46 def push(*items) items = items.dup EM.schedule { items.each { |i| @subs.values.each { |s| s.call i } } } end
Add items to the channel, which are pushed out to all subscribers.
Also aliased as: <<
Source
# File lib/em/channel.rb, line 30 def subscribe(*a, &b) name = gen_id EM.schedule { @subs[name] = EM::Callback(*a, &b) } name end
Takes any arguments suitable for EM::Callback() and returns a subscriber id for use when unsubscribing.
@return [Integer] Subscribe identifier @see unsubscribe
Source
# File lib/em/channel.rb, line 41 def unsubscribe(name) EM.schedule { @subs.delete name } end
Removes subscriber from the list.
@param [Integer] Subscriber identifier @see subscribe