mirror of
https://git.sr.ht/~ashkeel/strimertul
synced 2024-09-20 02:00:49 +00:00
aaffaebe55
Refactor Twitch client and bot so it can be closed and reopened with a different config. Add a cancellation function to subscription functions so they can be cancelled. Use http.Handler instead of HandlerFunc for custom routes
40 lines
821 B
Go
40 lines
821 B
Go
package utils
|
|
|
|
import "git.sr.ht/~hamcha/containers"
|
|
|
|
type PubSub[T Comparable] struct {
|
|
subscribers *containers.RWSync[[]T]
|
|
}
|
|
|
|
func NewPubSub[T Comparable]() *PubSub[T] {
|
|
return &PubSub[T]{
|
|
subscribers: containers.NewRWSync([]T{}),
|
|
}
|
|
}
|
|
|
|
func (p *PubSub[T]) Subscribe(handler T) {
|
|
p.subscribers.Set(append(p.subscribers.Get(), handler))
|
|
}
|
|
|
|
func (p *PubSub[T]) Unsubscribe(handler T) {
|
|
arr := p.subscribers.Get()
|
|
// Use slice trick to in-place remove entry if found
|
|
for index := range arr {
|
|
if arr[index].Equals(handler) {
|
|
arr[index] = arr[len(arr)-1]
|
|
p.subscribers.Set(arr[:len(arr)-1])
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *PubSub[T]) Subscribers() []T {
|
|
return p.subscribers.Get()
|
|
}
|
|
|
|
func (p *PubSub[T]) Copy(other *PubSub[T]) {
|
|
for _, subscriber := range other.Subscribers() {
|
|
p.Subscribe(subscriber)
|
|
}
|
|
}
|