Skip to content

Commit 3c24c3a

Browse files
committed
Add Unsubscribe method
1 parent 0350a61 commit 3c24c3a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

2020/go-pubsub/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module example.com
2+
3+
go 1.22.5

2020/go-pubsub/pubsub-close.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package main
66

77
import (
88
"fmt"
9+
"slices"
910
"sync"
1011
"time"
1112
)
@@ -30,6 +31,15 @@ func (ps *Pubsub) Subscribe(topic string, ch chan string) {
3031
ps.subs[topic] = append(ps.subs[topic], ch)
3132
}
3233

34+
func (ps *Pubsub) Unsubscribe(topic string, ch chan string) {
35+
ps.mu.Lock()
36+
defer ps.mu.Unlock()
37+
38+
ps.subs[topic] = slices.DeleteFunc(ps.subs[topic], func(c chan string) bool {
39+
return c == ch
40+
})
41+
}
42+
3343
func (ps *Pubsub) Publish(topic string, msg string) {
3444
ps.mu.RLock()
3545
defer ps.mu.RUnlock()
@@ -94,6 +104,14 @@ func main() {
94104
pub("tech", "drones")
95105

96106
time.Sleep(50 * time.Millisecond)
107+
108+
ps.Unsubscribe("travel", ch2)
109+
pub("travel", "hiking")
110+
time.Sleep(50 * time.Millisecond)
111+
ps.Unsubscribe("travel", ch3)
112+
pub("travel", "hiking")
113+
time.Sleep(50 * time.Millisecond)
114+
97115
ps.Close()
98116
time.Sleep(50 * time.Millisecond)
99117
}

0 commit comments

Comments
 (0)