-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscriber.go
64 lines (55 loc) · 1.39 KB
/
subscriber.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package asyncp
import (
"context"
"log"
"sync"
"github.com/geniusrabbit/notificationcenter/v2"
)
// Receiver defines the processing interface.
// This handler used for processing of the input messages from the stream
type Receiver = notificationcenter.Receiver
// Subscriber defines the interface of subscribing for some
// event stream processing
type Subscriber = notificationcenter.Subscriber
// ProxySubscriber defineds the multiple subscriber object
type ProxySubscriber struct {
subs []Subscriber
}
// NewProxySubscriber object from list of subscribers
func NewProxySubscriber(subs ...Subscriber) Subscriber {
if len(subs) == 1 {
return subs[0]
}
return &ProxySubscriber{subs: subs}
}
// Subscribe new handler for the stream
func (prx *ProxySubscriber) Subscribe(ctx context.Context, h Receiver) error {
for _, sub := range prx.subs {
if err := sub.Subscribe(ctx, h); err != nil {
return err
}
}
return nil
}
// Listen starts processing queue
func (prx *ProxySubscriber) Listen(ctx context.Context) (err error) {
var w sync.WaitGroup
for _, sub := range prx.subs {
w.Add(1)
go func(sub Subscriber) {
if err = sub.Listen(ctx); err != nil {
log.Printf("%t: %s", sub, err.Error())
}
w.Done()
}(sub)
}
w.Wait()
return err
}
// Close all proxy subscribers
func (prx *ProxySubscriber) Close() error {
for _, sub := range prx.subs {
_ = sub.Close()
}
return nil
}