Class: Concurrent::CopyOnNotifyObserverSet
- Inherits:
-
Object
- Object
- Concurrent::CopyOnNotifyObserverSet
- Defined in:
- lib/concurrent/copy_on_notify_observer_set.rb
Overview
A thread safe observer set implemented using copy-on-read approach: observers are added and removed from a thread safe collection; every time a notification is required the internal data structure is copied to prevent concurrency issues
Instance Method Summary collapse
-
#add_observer(observer, func = :update) ⇒ Symbol
Adds an observer to this set.
-
#count_observers ⇒ Integer
The observers count.
-
#delete_observer(observer) ⇒ Object
The deleted observer.
-
#delete_observers ⇒ CopyOnWriteObserverSet
Deletes all observers.
-
#initialize ⇒ CopyOnNotifyObserverSet
constructor
A new instance of CopyOnNotifyObserverSet.
-
#notify_and_delete_observers(*args, &block) ⇒ CopyOnWriteObserverSet
Notifies all registered observers with optional args and deletes them.
-
#notify_observers(*args, &block) ⇒ CopyOnWriteObserverSet
Notifies all registered observers with optional args.
Constructor Details
#initialize ⇒ CopyOnNotifyObserverSet
Returns a new instance of CopyOnNotifyObserverSet.
9 10 11 12 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 9 def initialize @mutex = Mutex.new @observers = {} end |
Instance Method Details
#add_observer(observer, func = :update) ⇒ Symbol
Adds an observer to this set
18 19 20 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 18 def add_observer(observer, func=:update) @mutex.synchronize { @observers[observer] = func } end |
#count_observers ⇒ Integer
Returns the observers count.
37 38 39 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 37 def count_observers @mutex.synchronize { @observers.count } end |
#delete_observer(observer) ⇒ Object
Returns the deleted observer.
24 25 26 27 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 24 def delete_observer(observer) @mutex.synchronize { @observers.delete(observer) } observer end |
#delete_observers ⇒ CopyOnWriteObserverSet
Deletes all observers
31 32 33 34 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 31 def delete_observers @mutex.synchronize { @observers.clear } self end |
#notify_and_delete_observers(*args, &block) ⇒ CopyOnWriteObserverSet
Notifies all registered observers with optional args and deletes them.
55 56 57 58 59 60 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 55 def notify_and_delete_observers(*args, &block) observers = duplicate_and_clear_observers notify_to(observers, *args, &block) self end |
#notify_observers(*args, &block) ⇒ CopyOnWriteObserverSet
Notifies all registered observers with optional args
44 45 46 47 48 49 |
# File 'lib/concurrent/copy_on_notify_observer_set.rb', line 44 def notify_observers(*args, &block) observers = @mutex.synchronize { @observers.dup } notify_to(observers, *args, &block) self end |