go-tdlib/client/listener.go

67 lines
1.1 KiB
Go
Raw 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 {
2018-10-23 12:38:10 +00:00
mu sync.Mutex
isActive bool
Updates chan 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
close(listener.Updates)
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
}