hypr/subscribe_event.go

37 lines
649 B
Go
Raw Permalink Normal View History

2024-02-09 20:57:18 +01:00
package hypr
import (
"bufio"
2024-02-09 21:30:14 +01:00
"context"
2024-02-09 20:57:18 +01:00
"strings"
"git.milar.in/milarin/slices"
)
2024-02-15 14:41:37 +01:00
func (i *Client) Subscribe(ctx context.Context, events ...EventType) (<-chan Event, error) {
2024-02-09 20:57:18 +01:00
r, err := readSocketRaw(i.EventSocketPath(), strings.NewReader(""))
if err != nil {
return nil, err
}
out := make(chan Event, 10)
eventMap := slices.ToStructMap(events)
allEvents := len(events) == 0
2024-02-09 20:57:18 +01:00
go func() {
defer r.Close()
defer close(out)
sc := bufio.NewScanner(r)
2024-02-09 21:30:14 +01:00
for ctx.Err() == nil && sc.Scan() {
2024-02-09 20:57:18 +01:00
event := parseEvent(sc.Text())
if _, ok := eventMap[event.Type]; allEvents || ok {
2024-02-09 20:57:18 +01:00
out <- event
}
}
}()
return out, nil
}