Files
NebulaLauncher/Nebula.Shared/Configurations/ConVarObserver.cs

67 lines
2.0 KiB
C#
Raw Normal View History

2025-08-06 21:29:00 +03:00
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Nebula.Shared.Services;
namespace Nebula.Shared.Configurations;
public sealed class ConVarObserver<T> : IDisposable, INotifyPropertyChanged, INotifyPropertyChanging
{
private readonly ConVar<T> _convar;
private readonly ConfigurationService _configurationService;
private T? _value;
private ConfigurationService.OnConfigurationChangedDelegate<T> _delegate;
2025-08-07 22:34:25 +03:00
public bool HasValue => Value != null;
2025-08-06 21:29:00 +03:00
public T? Value
{
get => _value;
set => _configurationService.SetConfigValue(_convar, value);
}
public ConVarObserver(ConVar<T> convar, ConfigurationService configurationService)
{
_convar = convar;
_convar.OnValueChanged += OnValueChanged;
_configurationService = configurationService;
_delegate += OnValueChanged;
OnValueChanged(configurationService.GetConfigValue(_convar));
}
private void OnValueChanged(T? value)
{
OnPropertyChanging(nameof(Value));
2025-08-07 22:34:25 +03:00
OnPropertyChanging(nameof(HasValue));
2025-08-06 21:29:00 +03:00
if(value is null && _value is null)
return;
if (_value is not null && _value.Equals(value))
return;
_value = value;
OnPropertyChanged(nameof(Value));
2025-08-07 22:34:25 +03:00
OnPropertyChanged(nameof(HasValue));
2025-08-06 21:29:00 +03:00
}
public void Dispose()
{
_convar.OnValueChanged -= OnValueChanged;
}
public static implicit operator T? (ConVarObserver<T> convar) => convar.Value;
public event PropertyChangingEventHandler? PropertyChanging;
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanging([CallerMemberName] string? propertyName = null)
{
PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
}
}