-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
63 lines (52 loc) · 1.18 KB
/
example_test.go
File metadata and controls
63 lines (52 loc) · 1.18 KB
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
53
54
55
56
57
58
59
60
61
62
63
package pubsub_test
import (
"context"
"fmt"
"github.com/denpeshkov/pubsub"
"golang.org/x/sync/errgroup"
)
func Example() {
// Create the PubSub.
ps := pubsub.New[string]()
ctx, cancel := context.WithCancel(context.Background())
g, ctx := errgroup.WithContext(ctx)
// Start the PubSub.
g.Go(func() error {
ps.Run(ctx)
return nil
})
// Subscribe to topics.
sub, err := ps.Subscribe(100, "topic1", "topic2")
if err != nil {
panic(err)
}
defer func() { _ = ps.Unsubscribe(sub) }()
// Start a goroutine to receive the messages.
g.Go(func() error {
for msg := range sub.Messages() {
fmt.Println("Received message:", msg)
}
return nil
})
// Publish to topics.
for i := range 3 {
if err := ps.Publish(context.Background(), fmt.Sprintf("foo_%d", i), "topic1"); err != nil {
panic(err)
}
if err := ps.Publish(context.Background(), fmt.Sprintf("bar_%d", i), "topic1"); err != nil {
panic(err)
}
}
// Stop the PubSub.
cancel()
if err := g.Wait(); err != nil {
panic(err)
}
// Output:
// Received message: foo_0
// Received message: bar_0
// Received message: foo_1
// Received message: bar_1
// Received message: foo_2
// Received message: bar_2
}