-
Notifications
You must be signed in to change notification settings - Fork 5
/
subscription.go
45 lines (41 loc) · 1008 Bytes
/
subscription.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
42
43
44
45
package apifu
import (
"context"
"reflect"
)
// SubscriptionSourceStream defines the source stream for a subscription.
type SubscriptionSourceStream struct {
// A channel of events. The channel can be of any type.
EventChannel any
// Stop is invoked when the subscription should be stopped and the event channel should be
// closed.
Stop func()
}
// Run drives the stream until it's closed or until the given context is cancelled.
func (s *SubscriptionSourceStream) Run(ctx context.Context, onEvent func(interface{})) error {
eventChannel := reflect.ValueOf(s.EventChannel)
ctxChannel := reflect.ValueOf(ctx.Done())
selectCases := []reflect.SelectCase{
{
Dir: reflect.SelectRecv,
Chan: ctxChannel,
},
{
Dir: reflect.SelectRecv,
Chan: eventChannel,
},
}
for {
chosen, recv, recvOK := reflect.Select(selectCases)
if chosen == 0 {
// ctx.Done()
return ctx.Err()
}
// s.EventChannel
if recvOK {
onEvent(recv.Interface())
} else {
return nil
}
}
}