github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/realtime/subscriber.go (about) 1 package realtime 2 3 import ( 4 "github.com/cozy/cozy-stack/pkg/prefixer" 5 ) 6 7 // Subscriber is used to subscribe to several doctypes 8 type Subscriber struct { 9 prefixer.Prefixer 10 Channel EventsChan 11 hub Hub 12 running chan struct{} 13 } 14 15 // EventsChan is a chan of events 16 type EventsChan chan *Event 17 18 func newSubscriber(hub Hub, db prefixer.Prefixer) *Subscriber { 19 return &Subscriber{ 20 Prefixer: db, 21 Channel: make(chan *Event, 100), 22 hub: hub, 23 running: make(chan struct{}), 24 } 25 } 26 27 // Subscribe adds a listener for events on a whole doctype 28 func (sub *Subscriber) Subscribe(doctype string) { 29 if sub.hub == nil { 30 return 31 } 32 key := topicKey(sub, doctype) 33 sub.hub.subscribe(sub, key) 34 } 35 36 // Unsubscribe removes a listener for events on a whole doctype 37 func (sub *Subscriber) Unsubscribe(doctype string) { 38 if sub.hub == nil { 39 return 40 } 41 key := topicKey(sub, doctype) 42 sub.hub.unsubscribe(sub, key) 43 } 44 45 // Watch adds a listener for events for a specific document (doctype+id) 46 func (sub *Subscriber) Watch(doctype, id string) { 47 if sub.hub == nil { 48 return 49 } 50 key := topicKey(sub, doctype) 51 sub.hub.watch(sub, key, id) 52 } 53 54 // Unwatch removes a listener for events for a specific document (doctype+id) 55 func (sub *Subscriber) Unwatch(doctype, id string) { 56 if sub.hub == nil { 57 return 58 } 59 key := topicKey(sub, doctype) 60 sub.hub.unwatch(sub, key, id) 61 } 62 63 // Close will unsubscribe to all topics and the subscriber should no longer be 64 // used after that. 65 func (sub *Subscriber) Close() { 66 if sub.hub == nil { 67 return 68 } 69 close(sub.running) 70 go sub.hub.close(sub) 71 sub.hub = nil 72 }