class Rox::Core::NotificationListener

Public Class Methods

new(listen_url, app_key) click to toggle source
# File lib/rox/core/notifications/notification_listener.rb, line 6
def initialize(listen_url, app_key)
  @listen_url = listen_url
  @app_key = app_key
  @handlers = {}
end

Public Instance Methods

on(event_name, &handler) click to toggle source
# File lib/rox/core/notifications/notification_listener.rb, line 12
def on(event_name, &handler)
  @handlers[event_name] ||= []
  @handlers[event_name] << handler
end
start() click to toggle source
# File lib/rox/core/notifications/notification_listener.rb, line 17
def start
  sse_url = "#{@listen_url.chomp('/')}/#{@app_key}"
  @thread = Thread.new do
    EM.run do
      source = EventMachine::EventSource.new(sse_url)
      @handlers.each do |event_name, event_handlers|
        event_handlers.each do |handler|
          source.on event_name do |data|
            # Start new thread to allow the handler to stop the Listener (terminate the current thread)
            # and continue handler code execution without interruption
            handler_thread = Thread.new do
              handler.call(data)
            end
            handler_thread.join
          end
        end
      end
      source.start
    end
  end
end
stop() click to toggle source
# File lib/rox/core/notifications/notification_listener.rb, line 39
def stop
  @thread&.terminate
  @thread = nil
end