Skip to content

Commit

Permalink
misc: add property watcher
Browse files Browse the repository at this point in the history
  • Loading branch information
revam committed May 12, 2024
1 parent ca6a246 commit 8ab5db4
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Shokofin/Utils/PropertyWatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;

namespace Shokofin.Utils;

public class PropertyWatcher<T>
{
private readonly Func<T> _valueGetter;

private bool _continueMonitoring;

public T LastKnownValue { get; private set; }

public event EventHandler<T> OnValueChanged;

public PropertyWatcher(Func<T> valueGetter)

Check warning on line 16 in Shokofin/Utils/PropertyWatcher.cs

View workflow job for this annotation

GitHub Actions / Build & Release (Unstable)

Non-nullable event 'OnValueChanged' must contain a non-null value when exiting constructor. Consider declaring the event as nullable.
{
_valueGetter = valueGetter;
LastKnownValue = _valueGetter();
}

public void StartMonitoring(int delayInMilliseconds)
{
_continueMonitoring = true;
LastKnownValue = _valueGetter();
Task.Run(async () => {
while (_continueMonitoring) {
await Task.Delay(delayInMilliseconds);
CheckForChange();
}
});
}

public void StopMonitoring()
{
_continueMonitoring = false;
}

private void CheckForChange()
{
var currentValue = _valueGetter()!;
if (!LastKnownValue!.Equals(currentValue)) {
OnValueChanged?.Invoke(null, currentValue);
LastKnownValue = currentValue;
}
}
}

0 comments on commit 8ab5db4

Please sign in to comment.