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)
# File lib/em/channel.rb, line 15 def initialize @subs = {} @uid = 0 end
Fetches one message from the channel.
# File lib/em/channel.rb, line 48 def pop(*a, &b) EM.schedule { name = subscribe do |*args| unsubscribe(name) EM::Callback(*a, &b).call(*args) end } end
Add items to the channel, which are pushed out to all subscribers.
# File lib/em/channel.rb, line 41 def push(*items) items = items.dup EM.schedule { items.each { |i| @subs.values.each { |s| s.call i } } } end
Takes any arguments suitable for EM::Callback() and returns a subscriber id for use when unsubscribing.
@return [Integer] Subscribe identifier @see unsubscribe
# File lib/em/channel.rb, line 25 def subscribe(*a, &b) name = gen_id EM.schedule { @subs[name] = EM::Callback(*a, &b) } name end
Removes subscriber from the list.
@param [Integer] Subscriber identifier @see subscribe
# File lib/em/channel.rb, line 36 def unsubscribe(name) EM.schedule { @subs.delete name } end
@private
# File lib/em/channel.rb, line 60 def gen_id @uid += 1 end