module Quartz::Observable

Overview

The Observer pattern (publish/subscribe) provides a simple mechanism for one object to inform a set of interested third-party objects when its state changes.

The notifying class mixes in the Observable module, which provides the methods for managing the associated observer objects. The observable object must call #notify_observers to notify its observers.

An observer object must conforms to the Observer protocol. It subscribes to updates using #add_observer.

Example 1: Observing model state changes

class MyObserver
  include Quartz::Observer

  def update(observable, info)
    if observable.is_a?(MyModel)
      model = observable.as(MyModel)
      puts "#{model.name} changed its state to #{model.phase}"
    end
  end
end

model = MyModel.new("mymodel")
model.add_observer(MyObserver.new)
Quartz::Simulation.new(model).simulate

Example 2: Observing outputs on a port.

class MyObserver
  include Quartz::Observer

  def update(observable, info)
    if observable.is_a?(Port) && info
      puts "port '#{port.name}' sends value '#{info[:payload]}'"
    end
  end
end

model = MyModel.new("mymodel")
model.output_port(:out).add_observer(MyObserver.new)
Quartz::Simulation.new(model).simulate

Direct including types

Defined in:

quartz/observer.cr

Instance Method Summary

Instance Method Detail

def add_observer(observer : Observer) #

Adds observer to the list of observers so that it will receive future updates.


[View source]
def count_observers #

Returns the number of objects currently observing this object.


[View source]
def delete_observer(observer : Observer) : Bool #

Removes observer from the list of observers so that it will no longer receive updates.


[View source]
def notify_observers(info = nil) #

Notifies observers of a change in state. A dictionary, info, can be passed to observers that conforms to the Observer protocol.


[View source]