File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package hub
22
33import (
44 "fmt"
5+ "sync"
56)
67
78type 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
You can’t perform that action at this time.
0 commit comments