ProjectDDD/Assets/_DDD/_Scripts/GameUi/BaseUi/SimpleViewModel.cs
2025-08-25 05:12:05 +09:00

84 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace DDD
{
public abstract class SimpleViewModel : MonoBehaviour, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public virtual void Initialize() { }
public virtual void Cleanup() { }
/// <summary>
/// PropertyChanged 이벤트 발생
/// </summary>
/// <param name="propertyName">변경된 속성 이름 (자동으로 설정됨)</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (string.IsNullOrEmpty(propertyName)) return;
if (_updateDepth > 0)
{
// 배치 업데이트 중: 나중에 일괄 발행
_pendingNotifications.Add(propertyName);
return;
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// 필드 값 변경 및 PropertyChanged 이벤트 발생
/// </summary>
/// <typeparam name="T">필드 타입</typeparam>
/// <param name="field">변경할 필드 참조</param>
/// <param name="value">새로운 값</param>
/// <param name="propertyName">속성 이름 (자동으로 설정됨)</param>
/// <returns>값이 실제로 변경되었는지 여부</returns>
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
private int _updateDepth;
private readonly HashSet<string> _pendingNotifications = new();
protected void BeginUpdate()
{
_updateDepth++;
}
protected void EndUpdate()
{
if (_updateDepth == 0)
{
Debug.LogWarning("EndUpdate called without matching BeginUpdate.");
return;
}
_updateDepth--;
// 아직 상위 배치가 진행 중이면 플러시하지 않음
if (_updateDepth > 0) return;
if (_pendingNotifications.Count > 0)
{
// 복사 후 클리어(핸들러 내부에서 BeginUpdate가 호출되어도 안전)
var toNotify = new List<string>(_pendingNotifications);
_pendingNotifications.Clear();
foreach (var prop in toNotify)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
}
}
}