Skip to content

Commit

Permalink
feat: add support for checking when closed
Browse files Browse the repository at this point in the history
  • Loading branch information
ShindouMihou committed Sep 15, 2023
1 parent 2f6c0c0 commit 462c3c1
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,11 @@ func main() {
}
defer chismis.Close()
for {
if chismis.IsClosed() {
break
}
message := chismis.Poll()
if message != nil {
if message == nil {
continue
}
fmt.Println("received ", message.Event, " from ", message.Filename)
Expand Down
12 changes: 12 additions & 0 deletions chikador/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
type Chismis struct {
queue eventQueue
watcher *fsnotify.Watcher
closed bool
}

type Message struct {
Expand Down Expand Up @@ -46,6 +47,7 @@ func Watch(path string, opts ...Option) (*Chismis, error) {
chismis := &Chismis{
queue: eventQueue{},
watcher: watcher,
closed: false,
}
options2.kind(chismis)
return chismis, nil
Expand All @@ -61,6 +63,12 @@ func (chismis *Chismis) Poll() *Message {
return chismis.queue.poll()
}

// IsClosed checks whether this Chismis channel is already closed, important if you want to stop program immediately
// when closed.
func (chismis *Chismis) IsClosed() bool {
return chismis.closed
}

// Listen listens to events from the event queue, this is running in another goroutine and uses the same polling method
// internally.
//
Expand All @@ -69,6 +77,9 @@ func (chismis *Chismis) Poll() *Message {
func (chismis *Chismis) Listen(fn func(msg *Message)) {
go func() {
for {
if chismis.closed {
break
}
msg := chismis.Poll()
if msg == nil {
continue
Expand All @@ -80,5 +91,6 @@ func (chismis *Chismis) Listen(fn func(msg *Message)) {

// Close removes all watches and closes all event channels.
func (chismis *Chismis) Close() error {
chismis.closed = true
return chismis.watcher.Close()
}
5 changes: 4 additions & 1 deletion examples/polling/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ func main() {
}
defer chismis.Close()
for {
if chismis.IsClosed() {
break
}
message := chismis.Poll()
if message != nil {
if message == nil {
continue
}
fmt.Println("received ", message.Event, " from ", message.Filename)
Expand Down

0 comments on commit 462c3c1

Please sign in to comment.