Skip to content

Commit c0ee174

Browse files
author
Philipp Heckel
committed
Make publishing asynchronous
1 parent cc752cf commit c0ee174

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

server/topic.go

+13-7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func newTopic(id string, last time.Time) *topic {
2828
}
2929
}
3030

31+
// Subscribe subscribes to this topic
3132
func (t *topic) Subscribe(s subscriber) int {
3233
t.mu.Lock()
3334
defer t.mu.Unlock()
@@ -37,24 +38,29 @@ func (t *topic) Subscribe(s subscriber) int {
3738
return subscriberID
3839
}
3940

41+
// Unsubscribe removes the subscription from the list of subscribers
4042
func (t *topic) Unsubscribe(id int) {
4143
t.mu.Lock()
4244
defer t.mu.Unlock()
4345
delete(t.subscribers, id)
4446
}
4547

48+
// Publish asynchronously publishes to all subscribers
4649
func (t *topic) Publish(m *message) error {
47-
t.mu.Lock()
48-
defer t.mu.Unlock()
49-
t.last = time.Now()
50-
for _, s := range t.subscribers {
51-
if err := s(m); err != nil {
52-
log.Printf("error publishing message to subscriber")
50+
go func() {
51+
t.mu.Lock()
52+
defer t.mu.Unlock()
53+
t.last = time.Now()
54+
for _, s := range t.subscribers {
55+
if err := s(m); err != nil {
56+
log.Printf("error publishing message to subscriber")
57+
}
5358
}
54-
}
59+
}()
5560
return nil
5661
}
5762

63+
// Subscribers returns the number of subscribers to this topic
5864
func (t *topic) Subscribers() int {
5965
t.mu.Lock()
6066
defer t.mu.Unlock()

0 commit comments

Comments
 (0)