// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace OwlCore.WinUI.Threading
{
///
/// Implements a weak event listener that allows the owner to be garbage
/// collected if its only remaining link is an event handler.
///
/// Type of instance listening for the event.
/// Type of source for the event.
/// Type of event arguments for the event.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public sealed class WeakEventListener
where TInstance : class
{
///
/// WeakReference to the instance listening for the event.
///
private readonly WeakReference _weakInstance;
///
/// Initializes a new instance of the class.
///
/// Instance subscribing to the event.
public WeakEventListener(TInstance instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
_weakInstance = new WeakReference(instance);
}
///
/// Gets or sets the method to call when the event fires.
///
public Action? OnEventAction { get; set; }
///
/// Gets or sets the method to call when detaching from the event.
///
public Action>? OnDetachAction { get; set; }
///
/// Handler for the subscribed event calls OnEventAction to handle it.
///
/// Event source.
/// Event arguments.
public void OnEvent(TSource source, TEventArgs eventArgs)
{
var target = (TInstance)_weakInstance.Target;
if (target != null)
{
// Call registered action
OnEventAction?.Invoke(target, source, eventArgs);
}
else
{
// Detach from event
Detach();
}
}
///
/// Detaches from the subscribed event.
///
public void Detach()
{
OnDetachAction?.Invoke(this);
OnDetachAction = null;
}
}
}