Class: EventMachine::Channel
- Inherits:
-
Object
- Object
- EventMachine::Channel
- Defined in:
- lib/em/channel.rb
Overview
Provides a simple thread-safe way to transfer data between (typically) long running tasks in defer and event loop thread.
Instance Method Summary collapse
-
#initialize ⇒ Channel
constructor
A new instance of Channel.
-
#pop(*a, &b) ⇒ Object
Fetches one message from the channel.
-
#push(*items) ⇒ Object
(also: #<<)
Add items to the channel, which are pushed out to all subscribers.
-
#subscribe(*a, &b) ⇒ Integer
Takes any arguments suitable for EM::Callback() and returns a subscriber id for use when unsubscribing.
-
#unsubscribe(name) ⇒ Object
Removes subscriber from the list.
Constructor Details
#initialize ⇒ Channel
Returns a new instance of Channel.
15 16 17 18 |
# File 'lib/em/channel.rb', line 15 def initialize @subs = {} @uid = 0 end |
Instance Method Details
#pop(*a, &b) ⇒ Object
Fetches one message from the channel.
48 49 50 51 52 53 54 55 |
# 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 |
#push(*items) ⇒ Object Also known as: <<
Add items to the channel, which are pushed out to all subscribers.
41 42 43 44 |
# 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 |
#subscribe(*a, &b) ⇒ Integer
Takes any arguments suitable for EM::Callback() and returns a subscriber id for use when unsubscribing.
25 26 27 28 29 30 |
# File 'lib/em/channel.rb', line 25 def subscribe(*a, &b) name = gen_id EM.schedule { @subs[name] = EM::Callback(*a, &b) } name end |
#unsubscribe(name) ⇒ Object
Removes subscriber from the list.
36 37 38 |
# File 'lib/em/channel.rb', line 36 def unsubscribe(name) EM.schedule { @subs.delete name } end |