-
Notifications
You must be signed in to change notification settings - Fork 0
/
doc_test.go
50 lines (40 loc) · 1.05 KB
/
doc_test.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
package gopubsub_test
import (
"context"
"github.com/kauche/gopubsub"
)
type greetingMessage struct {
greeting string
}
func Example() {
// Create a topic with a type which you want to publish and subscribe.
topic := gopubsub.NewTopic[greetingMessage]()
ctx, cancel := context.WithCancel(context.Background())
terminated := make(chan struct{})
go func() {
// Start the topic. This call of Start blocks until the context is canceled.
if err := topic.Start(ctx); err != nil {
println(err)
return
}
terminated <- struct{}{}
}()
// Publish a message to the topic. This call of Publish is non-blocking.
if err := topic.Publish(greetingMessage{greeting: "Hello, gopubsub!"}); err != nil {
cancel()
println(err)
return
}
// Subscribe the topic. This call of Subscribe is non-blocking.
// The function passed to Subscribe is called when a message is published to the topic.
err := topic.Subscribe(func(message greetingMessage) {
println(message.greeting)
})
if err != nil {
cancel()
println(err)
return
}
cancel()
<-terminated
}