Table of Contents

Class ObserverPattern<T>

A lightweight, generic implementation of the Observer pattern. Maintains a list of subscriber callbacks and notifies them all when a value is published. Prefer this over C# events when you need runtime subscribe/unsubscribe with no delegate leak risk, or when you want to store the observer list as a field rather than as a static event.

public class ObserverPattern<T>

Type Parameters

T

The type of data passed to each observer when notified.

Inheritance
ObserverPattern<T>
Inherited Members

Examples

var onHealthChanged = new ObserverPattern<int>();
onHealthChanged.Subscribe(hp => Debug.Log($"HP: {hp}"));
onHealthChanged.NotifyObservers(50);

Methods

NotifyObservers(T)

Invokes all registered observer callbacks with the supplied value. Null callbacks are skipped safely.

public void NotifyObservers(T value)

Parameters

value T

The data to broadcast to every observer.

Subscribe(Action<T>)

Registers a callback as an observer. Duplicate subscriptions are ignored.

public void Subscribe(Action<T> observer)

Parameters

observer Action<T>

The callback to invoke when a notification is broadcast.

Unsubscribe(Action<T>)

Removes a previously registered observer callback.

public void Unsubscribe(Action<T> observer)

Parameters

observer Action<T>

The callback to remove.