Last active
April 12, 2025 04:30
-
-
Save adammyhre/3c5e6a50dba6b808ab74651aff5af57c to your computer and use it in GitHub Desktop.
Generic Observable with ValueChanged Action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
[Serializable] | |
public class Observable<T> { | |
private T value; | |
public event Action<T> ValueChanged; | |
public T Value { | |
get => value; | |
set => Set(value); | |
} | |
public static implicit operator T(Observable<T> observable) => observable.value; | |
public Observable(T value, Action<T> onValueChanged = null) { | |
this.value = value; | |
if (onValueChanged != null) | |
ValueChanged += onValueChanged; | |
} | |
public void Set(T value) { | |
if (EqualityComparer<T>.Default.Equals(this.value, value)) | |
return; | |
this.value = value; | |
Invoke(); | |
} | |
public void Invoke() { | |
ValueChanged?.Invoke(value); | |
} | |
public void AddListener(Action<T> handler) { | |
ValueChanged += handler; | |
} | |
public void RemoveListener(Action<T> handler) { | |
ValueChanged -= handler; | |
} | |
public void Dispose() { | |
ValueChanged = null; | |
value = default; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment