base-golang/pkg/observable/subscriber.go

34 lines
434 B
Go
Raw Permalink Normal View History

2024-07-23 10:23:43 +08:00
package observable
import (
"sync"
)
type Subscription <-chan any
type Subscriber struct {
buffer chan any
once sync.Once
}
func (s *Subscriber) Emit(item any) {
s.buffer <- item
}
func (s *Subscriber) Out() Subscription {
return s.buffer
}
func (s *Subscriber) Close() {
s.once.Do(func() {
close(s.buffer)
})
}
func newSubscriber() *Subscriber {
sub := &Subscriber{
buffer: make(chan any, 200),
}
return sub
}