Class: Async::Matrix::Notifier

Inherits:
Object
  • Object
show all
Defined in:
lib/async/matrix/notifier.rb

Overview

Waitable event bus. Signal it when events arrive; /sync handlers wait on it with a timeout.

notifier = Async::Matrix::Notifier.new

# In a /sync handler fiber (blocks until signalled or timeout):
notifier.wait(timeout: 30) { check_for_events() }

# After persisting an event (wakes all waiting fibers):
notifier.signal

Instance Method Summary collapse

Constructor Details

#initializeNotifier

Returns a new instance of Notifier.



25
26
27
# File 'lib/async/matrix/notifier.rb', line 25

def initialize
  @condition = Async::Condition.new
end

Instance Method Details

#signalObject

Wake all waiting fibers.



30
31
32
# File 'lib/async/matrix/notifier.rb', line 30

def signal
  @condition.signal
end

#wait(timeout: 30, &block) ⇒ Object

Block up to timeout seconds. Yields to check for data after each wake-up; returns the block’s value as soon as it is truthy. Returns the block’s value (possibly nil/false) when time runs out.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/async/matrix/notifier.rb', line 37

def wait(timeout: 30, &block)
  deadline = Time.now + timeout

  loop do
    result = yield
    return result if result

    remaining = deadline - Time.now
    return result if remaining <= 0

    begin
      Async::Task.current.with_timeout(remaining) do
        @condition.wait
      end
    rescue Async::TimeoutError
      return yield
    end
  end
end