go-tdlib/client/listener.go

74 lines
1.2 KiB
Go
Raw Permalink Normal View History

2018-09-10 22:30:14 +00:00
package client
import (
2018-10-23 12:38:10 +00:00
"sync"
2018-09-10 22:30:14 +00:00
)
func newListenerStore() *listenerStore {
2018-10-23 12:38:10 +00:00
return &listenerStore{
listeners: []*Listener{},
}
2018-09-10 22:30:14 +00:00
}
type listenerStore struct {
2018-10-23 12:38:10 +00:00
sync.Mutex
listeners []*Listener
2018-09-10 22:30:14 +00:00
}
func (store *listenerStore) Add(listener *Listener) {
2018-10-23 12:38:10 +00:00
store.Lock()
defer store.Unlock()
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
store.listeners = append(store.listeners, listener)
2018-09-10 22:30:14 +00:00
}
func (store *listenerStore) Listeners() []*Listener {
2018-10-23 12:38:10 +00:00
store.Lock()
defer store.Unlock()
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
return store.listeners
2018-09-10 22:30:14 +00:00
}
func (store *listenerStore) gc() {
2018-10-23 12:38:10 +00:00
store.Lock()
defer store.Unlock()
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
oldListeners := store.listeners
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
store.listeners = []*Listener{}
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
for _, listener := range oldListeners {
if listener.IsActive() {
store.listeners = append(store.listeners, listener)
}
}
2018-09-10 22:30:14 +00:00
}
type Listener struct {
mu sync.Mutex
isActive bool
Updates chan Type
RawUpdates chan Type
Filter Type
2018-09-10 22:30:14 +00:00
}
func (listener *Listener) Close() {
2018-10-23 12:38:10 +00:00
listener.mu.Lock()
defer listener.mu.Unlock()
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
listener.isActive = false
if listener.Updates != nil {
close(listener.Updates)
}
if listener.RawUpdates != nil {
close(listener.RawUpdates)
}
2018-09-10 22:30:14 +00:00
}
func (listener *Listener) IsActive() bool {
2018-10-23 12:38:10 +00:00
listener.mu.Lock()
defer listener.mu.Unlock()
2018-09-10 22:30:14 +00:00
2018-10-23 12:38:10 +00:00
return listener.isActive
2018-09-10 22:30:14 +00:00
}