Observed<T>
Observed<T> is a class that wraps a value of type T
and allows subscribers to be notified when the value is changed.
Observed variables are variables that can notify subscribers when their value changes. This can be useful in game development for tracking and responding to changes in various game states or variables. For example, an observed variable could be used to track the player's health, the progress of a loading screen, or the score of a game. Subscribers can be set up to listen for changes to the observed variable and take some action in response, such as updating a UI element or triggering some other event. Observed variables can be particularly useful in situations where multiple game objects or systems need to stay in sync with the value of a particular variable.
Adding Subscribers
Subscribers can be added using the Subscribe
method, which takes an Action<T>
delegate as an argument. This delegate will be called whenever the value of the Observed<T>
instance is changed.
Removing Subscribers
Subscribers can be removed using the Unsubscribe
method, which takes an Action<T>
delegate as an argument.
Subscribe(Action<T> callback)
: Subscribes a callback function to theObserved<T>
instance. The callback function will be called whenever the value of theObserved<T>
instance changes.Unsubscribe(Action<T> callback)
: Unsubscribes a callback function from theObserved<T>
instance. The callback function will no longer be called when the value of theObserved<T>
instance changes.
Example
Setting the Value
The value of the Observed<T>
instance can be set using the Value
property. This will trigger the subscribers to be notified of the change.
Conversion to and from T
The Observed<T>
class includes implicit conversion operators for converting to and from the wrapped type T
. This allows it to be used in place of T
in most cases.
Clearing Subscriptions
All subscribers can be removed at once using the ClearSubscriptions
method.
Properties
SubscriberCount
Gets the number of subscribers registered for this observable.
HandleExceptions
A flag indicating whether exceptions thrown by subscribers should be handled or allowed to propagate.
Value
Gets or sets the current value of the observable. Setting the value will trigger the notification of subscribers if the value has changed.
Constructors
Observed()
Creates a new instance of the Observed class with a default value.
Observed(T initialValue)
Creates a new instance of the Observed class with the specified initial value.
Methods
Subscribe(Action<T> callback)
Registers a callback method to be notified when the value of the observable changes. If the callback method is already registered, it will not be added again.
Unsubscribe(Action<T> callback)
Unregisters a callback method from being notified when the value of the observable changes.
Last updated