Skip to content

Observed

The Observed<T> class in the ByteCobra.Observables namespace encapsulates a generic value of type T and provides notification capabilities whenever the value is altered. This class allows subscribing to changes in the value, making it ideal for scenarios where it's crucial to monitor value changes.

When the value is changed via the Value property, the NotifyChanged method is invoked to alert all subscribers about the change.

The HandleExceptions property allows for control over exception handling during notification dispatch. By setting this property, you can decide whether exceptions thrown during notification should be handled within the NotifyChanged method or should be thrown outside to be handled externally.

This class provides a foundation for building reactive programming paradigms within your applications, facilitating timely reactions to data changes and enhancing data-driven logic.

Properties

  • bool HandleExceptions: Determines whether exceptions during change notifications should be handled internally or thrown outside the class.

Methods

  • void Subscribe(Action<T> callback): Registers a callback to be invoked when the value changes.
  • void Unsubscribe(Action<T> callback): Unregisters a previously registered callback.
  • void ClearSubscriptions(): Clears all registered callbacks.
  • void NotifyChanged(): Manually triggers a notification of the value change.
  • void SetValueSilently(T value): Sets the value without triggering change notifications.
  • void Subscribe(Action callback): Registers a callback to be invoked when the value changes, without providing the new value.
  • void Unsubscribe(Action callback): Unregisters a previously registered callback, which was registered without providing the new value.

Example

var observedValue = new Observed<int>(10);

observedValue.Subscribe((newValue) =>
{
    Console.WriteLine($"Value changed to {newValue}");
});

observedValue.Value = 20; // Output: Value changed to 20