Sha256: 40ab71e3384867f096d8e2c75db198a224984b81852cb9b8c71a9e78faf7ea00

Contents?: true

Size: 1.53 KB

Versions: 44

Compression:

Stored size: 1.53 KB

Contents

module EventMachine
  # 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)
  #
  #
  class Channel
    def initialize
      @subs = {}
      @uid  = 0
    end

    # Return the number of current subscribers.
    def num_subscribers
      return @subs.size
    end

    # Takes any arguments suitable for EM::Callback() and returns a subscriber
    # id for use when unsubscribing.
    #
    # @return [Integer] Subscribe identifier
    # @see #unsubscribe
    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
    def unsubscribe(name)
      EM.schedule { @subs.delete name }
    end

    # Add items to the channel, which are pushed out to all subscribers.
    def push(*items)
      items = items.dup
      EM.schedule { items.each { |i| @subs.values.each { |s| s.call i } } }
    end
    alias << push

    # Fetches one message from the channel.
    def pop(*a, &b)
      EM.schedule {
        name = subscribe do |*args|
          unsubscribe(name)
          EM::Callback(*a, &b).call(*args)
        end
      }
    end

    private

    # @private
    def gen_id
      @uid += 1
    end
  end
end

Version data entries

44 entries across 41 versions & 6 rubygems

Version Path
devcycle-ruby-server-sdk-1.1.0 examples/sinatra/vendor/bundle/ruby/3.1.0/gems/eventmachine-1.2.7/lib/em/channel.rb
devcycle-ruby-server-sdk-1.1.0 examples/sinatra/vendor/bundle/ruby/2.6.0/gems/eventmachine-1.2.7/lib/em/channel.rb
devcycle-ruby-server-sdk-1.1.0 examples/sinatra/vendor/bundle/ruby/3.0.0/gems/eventmachine-1.2.7/lib/em/channel.rb
eventmachine-mkroman-1.3.0.dev.1 lib/em/channel.rb
wj_eventmachine-1.3.2 lib/em/channel.rb
wj_eventmachine-1.3.1 lib/em/channel.rb
wj_eventmachine-1.3.0.dev.1 lib/em/channel.rb
eventmachine-1.2.7-java lib/em/channel.rb
eventmachine-1.2.7-x64-mingw32 lib/em/channel.rb
eventmachine-1.2.7-x86-mingw32 lib/em/channel.rb
eventmachine-1.2.7 lib/em/channel.rb
eventmachine-1.2.6-x64-mingw32 lib/em/channel.rb
eventmachine-1.2.6-x86-mingw32 lib/em/channel.rb
eventmachine-1.2.6-java lib/em/channel.rb
eventmachine-1.2.6 lib/em/channel.rb
eventmachine-1.2.5-x86-mingw32 lib/em/channel.rb
eventmachine-1.2.5-x64-mingw32 lib/em/channel.rb
eventmachine-1.2.5-java lib/em/channel.rb
eventmachine-1.2.5 lib/em/channel.rb
eventmachine-1.2.3-x64-mingw32 lib/em/channel.rb