Skip to content

Commit

Permalink
feat: StartStopEventWrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinZikmund committed Nov 3, 2020
1 parent 522e8b3 commit be2b602
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/Uno.UWP/Helpers/StartStopEventWrapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;

namespace Uno.Helpers
{
internal class StartStopEventWrapper<TDelegate>
where TDelegate : Delegate
{
private readonly object _syncLock = new object();
private readonly Action _onFirst;
private readonly Action _onLast;

public StartStopEventWrapper(
Action onFirst,
Action onLast)
{
_onFirst = onFirst;
_onLast = onLast;
}

public TDelegate Event { get; private set; } = null;

public void AddHandler(TDelegate handler)
{
lock (_syncLock)
{
var firstSubscriber = Event == null;
Event = (TDelegate)Delegate.Combine(Event, handler);
if (firstSubscriber)
{
_onFirst();
}
}
}

public void RemoveHandler(TDelegate handler)
{
lock (_syncLock)
{
if (Event != null)
{
Event = (TDelegate)Delegate.Remove(Event, handler);
if (Event == null)
{
_onLast();
}
}
}
}
}
}

0 comments on commit be2b602

Please sign in to comment.