Sha256: 9bf3249d59b3aaf50aef3fe4ad6a52801c9a77feabf29c8a7b38e31172b73b68

Contents?: true

Size: 1.02 KB

Versions: 4

Compression:

Stored size: 1.02 KB

Contents

class TD::UpdateManager
  TIMEOUT = 30

  def initialize(td_client)
    @td_client = td_client
    @handlers = Concurrent::Array.new
    @mutex = Mutex.new
  end

  def add_handler(handler)
    @mutex.synchronize { @handlers << handler }
  end

  alias << add_handler

  def run(callback: nil)
    Thread.start do
      catch(:client_closed) { loop { handle_update(callback: callback) } }
      @mutex.synchronize { @handlers = [] }
    end
  end

  private

  attr_reader :handlers

  def handle_update(callback: nil)
    update = TD::Api.client_receive(@td_client, TIMEOUT)

    unless update.nil?
      extra  = update.delete('@extra')
      update = TD::Types.wrap(update)
      callback&.call(update)

      match_handlers!(update, extra).each { |h| h.async.run(update) }
    end
  end

  def match_handlers!(update, extra)
    @mutex.synchronize do
      matched_handlers = handlers.select { |h| h.match?(update, extra) }
      matched_handlers.each { |h| handlers.delete(h) if h.disposable? }
      matched_handlers
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
tdlib-ruby-3.0.1 lib/tdlib/update_manager.rb
tdlib-ruby-3.0.0 lib/tdlib/update_manager.rb
tdlib-ruby-2.2.0 lib/tdlib/update_manager.rb
tdlib-ruby-2.1.0 lib/tdlib/update_manager.rb