-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
52 lines (42 loc) · 1005 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"fmt"
"time"
"github.com/sauerbraten/pubsub"
)
type Update struct {
Seq int
Msg string
}
func main() {
broker := pubsub.NewBroker[Update]()
// subscribe to topic
updates, newPublisher := broker.Subscribe("topic")
if newPublisher != nil {
// maybe start producing updates to receive
go publish(newPublisher)
}
// subscribe many goroutines to the same topic
// and/or
// subscribe one goroutine to many different topics (requires additional publishing goroutines)
// receive updates until broker unsubscribes you
for update := range updates {
// process update
fmt.Printf("received update %d: %s\n", update.Seq, update.Msg)
}
// or, at some point, just unsubscribe
broker.Unsubscribe(updates, "topic")
}
func publish(pub *pubsub.Publisher[Update]) {
seq := 0
for {
select {
case <-pub.Stop:
pub.Close()
return
case <-time.After(1 * time.Second):
pub.Publish(Update{Seq: seq, Msg: time.Now().Format(time.RFC3339)})
seq++
}
}
}