Skip to content

Commit c0859e3

Browse files
committed
Expanded example to include channel closure example
1 parent 2cafeb0 commit c0859e3

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

examples_test.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package hub
22

33
import (
44
"fmt"
5+
"sync"
56
)
67

78
type ExampleEvent struct {
@@ -22,17 +23,29 @@ func Example() {
2223
fmt.Println(m["foo"])
2324
})
2425

25-
h.Subscribe(func(m string) {
26-
fmt.Println(m)
27-
})
26+
// use a wait group to demonstrate channel closure and to ensure all output happens
27+
w := new(sync.WaitGroup)
28+
w.Add(1)
29+
30+
c := make(chan string, 1)
31+
cancel, _ := h.Subscribe(c, func() { close(c) })
32+
go func() {
33+
defer w.Done()
34+
for m := range c {
35+
fmt.Println(m)
36+
}
37+
}()
2838

2939
h.Subscribe(ExampleListener{})
3040

3141
h.Publish(map[string]string{"foo": "bar"})
3242
h.Publish("an example message")
3343
h.Publish(ExampleEvent{Status: 123})
3444

35-
// Output:
45+
cancel()
46+
w.Wait()
47+
48+
// Unordered output:
3649
// bar
3750
// an example message
3851
// 123

0 commit comments

Comments
 (0)