Class: EventMachine::Channel

Inherits:
Object
  • Object
show all
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.

Examples:


channel = EventMachine::Channel.new
sid     = channel.subscribe { |msg| p [:got, msg] }

channel.push('hello world')
channel.unsubscribe(sid)

Instance Method Summary collapse

Constructor Details

#initializeChannel

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.

Returns:

  • (Integer)

    Subscribe identifier

See Also:



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.

Parameters:

  • Subscriber (Integer)

    identifier

See Also:



36
37
38
# File 'lib/em/channel.rb', line 36

def unsubscribe(name)
  EM.schedule { @subs.delete name }
end