Skip to content

Commit 94bc105

Browse files
authored
Merge pull request #29 from erkerkiii/feature/try-unsubscribe-from-signals
try unsubscribe feature added to signal center
2 parents ee79bca + 710c85f commit 94bc105

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

Gum.Signal/Core/SignalCenter.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,28 @@ public void Unsubscribe<T>(Action<T> action)
3434
}
3535
}
3636

37+
public bool TryUnsubscribe<T>(Action<T> action)
38+
{
39+
bool isSuccessful = false;
40+
lock (_lock)
41+
{
42+
for (int index = 0; index < _entries.Count; index++)
43+
{
44+
Entry entry = _entries[index];
45+
46+
if (entry.Delegate as Action<T> != action || !_entries.Contains(entry))
47+
{
48+
continue;
49+
}
50+
51+
_entries.Remove(entry);
52+
isSuccessful = true;
53+
}
54+
}
55+
56+
return isSuccessful;
57+
}
58+
3759
public void Fire<T>(T signal)
3860
{
3961
int hashCode = typeof(T).GetHashCode();

Tests/SignalTests/SignalCenterTests.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,23 @@ void FooAction(FooSignal _) { }
3939
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
4040
}
4141

42+
[Test]
43+
public void TryUnsubscribe()
44+
{
45+
void BarAction(BarSignal _) { }
46+
void FooAction(FooSignal _) { }
47+
48+
_signalCenter.Subscribe<BarSignal>(BarAction);
49+
Assert.IsTrue(_signalCenter.Exists<BarSignal>(BarAction));
50+
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
51+
bool isUnsubscribedFromBar = _signalCenter.TryUnsubscribe<BarSignal>(BarAction);
52+
bool isUnsubscribedFromFoo = _signalCenter.TryUnsubscribe<FooSignal>(FooAction);
53+
Assert.IsFalse(_signalCenter.Exists<FooSignal>(FooAction));
54+
Assert.IsFalse(_signalCenter.Exists<BarSignal>(BarAction));
55+
Assert.IsTrue(isUnsubscribedFromBar);
56+
Assert.IsFalse(isUnsubscribedFromFoo);
57+
}
58+
4259
[Test]
4360
public void Subscribe_And_Fire()
4461
{

0 commit comments

Comments
 (0)