2018-06-10 22:50:03 +08:00
|
|
|
package observable
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2022-03-16 12:10:13 +08:00
|
|
|
type Subscription <-chan any
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
type Subscriber struct {
|
2022-03-16 12:10:13 +08:00
|
|
|
buffer chan any
|
2018-06-10 22:50:03 +08:00
|
|
|
once sync.Once
|
|
|
|
}
|
|
|
|
|
2022-03-16 12:10:13 +08:00
|
|
|
func (s *Subscriber) Emit(item any) {
|
2020-10-20 17:44:39 +08:00
|
|
|
s.buffer <- item
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Subscriber) Out() Subscription {
|
2020-10-20 17:44:39 +08:00
|
|
|
return s.buffer
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Subscriber) Close() {
|
|
|
|
s.once.Do(func() {
|
2020-10-20 17:44:39 +08:00
|
|
|
close(s.buffer)
|
2018-06-10 22:50:03 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSubscriber() *Subscriber {
|
|
|
|
sub := &Subscriber{
|
2022-03-16 12:10:13 +08:00
|
|
|
buffer: make(chan any, 200),
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
return sub
|
|
|
|
}
|