-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
41 lines (38 loc) · 1014 Bytes
/
example.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
package pubsub
import (
"context"
"fmt"
"time"
)
func ExamplePubSub() {
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
pubSub := NewPubSub[int](ctx)
for i := 0; i < 4; i++ {
// create subscriber
go func(subscriberId int) {
defer fmt.Printf("Subscriber %d - finised.\n", subscriberId)
subscriberCtx, subscriberCancel := context.WithCancel(ctx)
subscriberChannel := pubSub.NewSubscriber(subscriberCtx)
for {
select {
case <-subscriberCtx.Done():
subscriberCancel()
return
case number := <-subscriberChannel:
fmt.Printf("Subscriber %d - got: number %d\n", subscriberId, number)
if number == subscriberId {
fmt.Printf("Subscriber %d - closes itself\n", subscriberId)
subscriberCancel() // close itself, will not receive any more messages
}
}
}
}(i)
}
// create publisher
publisherChannel := pubSub.NewPublisher()
for msg := 0; msg < 3; msg++ {
publisherChannel <- msg
time.Sleep(100 * time.Millisecond)
}
}