Table of Contents

Observable event Action<T> for .NET / Unity

Runtime/Reactive/ObservableAction.cs   HeaderDoc

(c) 2025 Sator Imaging, Licensed under the MIT License https://github.com/sator-imaging/Unity-Fundamentals

BASIC USAGE

// ObservableAction<int> is 24 bytes struct. recommend cast to interface once on instantiate.
private event Action<int>? Ev_MyEvent;
IObservableAction<int>? cache_MyEvent;
public IObservableAction<int> MyEvent => cache_MyEvent ??= new ObservableAction<T>(
    cb => Ev_MyEvent += cb,
    cb => Ev_MyEvent -= cb);

MyEvent.Subscribe(val => Debug.Log(val))  // register callback like Rx (reactive extensions)
    .AddTo(collection)  // add subscription to ICollection<IDisposable> for unsubscribing later
    .BindTo(token)      // or, bind to cancellation token to unsubscribe automatically when canceled.

MyEvent.Unsubscribe(existingAction);  // unsubscribe without disposable interface.

For parameter-less action events, VoidObservableAction can be used for. Of course you can use ObservableAction<object?> or something instead.

event Action<VoidObservableAction>? Ev_voidEvent;
public ObservableAction<VoidObservableAction> VoidEvent => new(x => Ev_voidEvent += x, x => Ev_voidEvent -= x);

Ev_voidEvent?.Invoke(VoidObservableAction.Default);  // use default to invoke event.