Skip to content

Commit

Permalink
try unsubscribe feature added to signal center
Browse files Browse the repository at this point in the history
  • Loading branch information
mhmtbtn committed Dec 29, 2024
1 parent ee79bca commit 710c85f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Gum.Signal/Core/SignalCenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,28 @@ public void Unsubscribe<T>(Action<T> action)
}
}

public bool TryUnsubscribe<T>(Action<T> action)
{
bool isSuccessful = false;
lock (_lock)
{
for (int index = 0; index < _entries.Count; index++)
{
Entry entry = _entries[index];

if (entry.Delegate as Action<T> != action || !_entries.Contains(entry))
{
continue;
}

_entries.Remove(entry);
isSuccessful = true;
}
}

return isSuccessful;
}

public void Fire<T>(T signal)
{
int hashCode = typeof(T).GetHashCode();
Expand Down
17 changes: 17 additions & 0 deletions Tests/SignalTests/SignalCenterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ void FooAction(FooSignal _) { }
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
}

[Test]
public void TryUnsubscribe()
{
void BarAction(BarSignal _) { }
void FooAction(FooSignal _) { }

_signalCenter.Subscribe<BarSignal>(BarAction);
Assert.IsTrue(_signalCenter.Exists<BarSignal>(BarAction));
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
bool isUnsubscribedFromBar = _signalCenter.TryUnsubscribe<BarSignal>(BarAction);
bool isUnsubscribedFromFoo = _signalCenter.TryUnsubscribe<FooSignal>(FooAction);
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
Assert.IsFalse(_signalCenter.Exists<BarSignal>(BarAction));
Assert.IsTrue(isUnsubscribedFromBar);
Assert.IsFalse(isUnsubscribedFromFoo);
}

[Test]
public void Subscribe_And_Fire()
{
Expand Down

0 comments on commit 710c85f

Please sign in to comment.