MCPcopy Create free account
hub / github.com/TheThingsNetwork/lorawan-stack / ExampleContextHandler

Function ExampleContextHandler

pkg/events/handler_test.go:100–131  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

98}
99
100func ExampleContextHandler() {
101 // Usually the context comes from somewhere else (e.g. a streaming RPC):
102 ctx, cancel := context.WithCancel(test.Context())
103 defer cancel()
104
105 eventChan := make(events.Channel, 2)
106 handler := events.ContextHandler(ctx, eventChan)
107
108 if err := events.Subscribe(ctx, []string{"example"}, nil, handler); err != nil {
109 panic(err)
110 }
111
112 // We automatically unsubscribe when he context gets canceled.
113
114 // From this moment on, "example" events will be delivered to the channel.
115 // As soon as the channel is full, events will be dropped, so it's probably a
116 // good idea to start handling the channel before subscribing.
117
118 go func() {
119 for {
120 select {
121 case <-ctx.Done():
122 // The ContextHandler will make sure that no events are delivered after
123 // the context is canceled, so it is now safe to close the channel:
124 close(eventChan)
125 return
126 case e := <-eventChan:
127 fmt.Printf("Received event %v\n", e)
128 }
129 }
130 }()
131}

Callers

nothing calls this directly

Calls 5

ContextFunction · 0.92
ContextHandlerFunction · 0.92
SubscribeFunction · 0.92
DoneMethod · 0.80
PrintfMethod · 0.45

Tested by

no test coverage detected