Skip to content

Instantly share code, notes, and snippets.

@simonwittber
Last active May 4, 2025 11:57
Show Gist options
  • Save simonwittber/d2e7089d3d18003fd7e1fef1a21ae5ca to your computer and use it in GitHub Desktop.
Save simonwittber/d2e7089d3d18003fd7e1fef1a21ae5ca to your computer and use it in GitHub Desktop.
Simply binding to anything using a VisualElement.schedule extension
// Usage: schedule.Watch(Func<T> getValue, Action<T> valueWasChanged)
// Eg: visualElement.schedule.Watch(() => myInstance.someProperty, i => visualElement.text = $"Value:{i}");
public class Observer<T>
{
private readonly Func<T> _getValue;
private readonly Action<T> _onChange;
private T _lastValue;
public Observer(Func<T> getValue, Action<T> onChange)
{
_getValue = getValue;
_onChange = onChange;
_lastValue = getValue();
}
public void Execute()
{
var newValue = _getValue();
if (!EqualityComparer<T>.Default.Equals(newValue, _lastValue))
{
_lastValue = newValue;
_onChange.Invoke(newValue);
}
}
}
public static class IVisualElementSchedulerExtensions
{
public static void Watch<T>(this IVisualElementScheduler scheduler, Func<T> GetValue, Action<T> OnChange)
{
scheduler.Execute(new Observer<T>(GetValue, OnChange).Execute).Until(() => false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment