go-observer
go-observer copied to clipboard
The way to stop observers periodically
Hello. Thanks for the interesting library!
We were faced with the need for a mechanism for stopping observers without stopping the property:
package main
import (
"fmt"
"math/rand"
"time"
"github.com/imkira/go-observer"
)
type stop struct{}
func main() {
obs := observer.NewProperty(0)
go func() {
t := time.Tick(time.Second * 3)
for {
select {
case <-t:
obs.Update(stop{}) // obs.Interrupt()
default:
obs.Update(rand.Int())
}
time.Sleep(time.Second)
}
}()
stream := obs.Observe()
for {
<-stream.Changes()
switch i := stream.Next().(type) {
case stop:
fmt.Println("exit")
case int:
fmt.Println(i)
}
/*
select {
case <-stream.Changes():
case <-stream.Interrupts():
}
*/
}
}
In the comments I suggested a new possible observer API. What do you think about that?