Clash.Meta/common/observable/subscriber.go

34 lines
465 B
Go
Raw Normal View History

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