2018-06-10 14:50:03 +00:00
|
|
|
package observable
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
type Subscription[T any] <-chan T
|
2018-06-10 14:50:03 +00:00
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
type Subscriber[T any] struct {
|
|
|
|
buffer chan T
|
2018-06-10 14:50:03 +00:00
|
|
|
once sync.Once
|
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
func (s *Subscriber[T]) Emit(item T) {
|
2020-10-20 09:44:39 +00:00
|
|
|
s.buffer <- item
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
func (s *Subscriber[T]) Out() Subscription[T] {
|
2020-10-20 09:44:39 +00:00
|
|
|
return s.buffer
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
func (s *Subscriber[T]) Close() {
|
2018-06-10 14:50:03 +00:00
|
|
|
s.once.Do(func() {
|
2020-10-20 09:44:39 +00:00
|
|
|
close(s.buffer)
|
2018-06-10 14:50:03 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
func newSubscriber[T any]() *Subscriber[T] {
|
|
|
|
sub := &Subscriber[T]{
|
|
|
|
buffer: make(chan T, 200),
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
return sub
|
|
|
|
}
|