2020-05-12 16:39:08 -04:00
|
|
|
package boba
|
2020-05-05 13:36:46 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Every is a subscription that ticks with the system clock at the given
|
2020-05-11 13:01:42 -04:00
|
|
|
// duration, similar to cron. It's particularly useful if you have several
|
|
|
|
// subscriptions that need to run in sync.
|
2020-05-11 22:13:34 -04:00
|
|
|
func Every(duration time.Duration, newMsg func(time.Time) Msg) Sub {
|
2020-05-05 13:36:46 -04:00
|
|
|
return func() Msg {
|
|
|
|
n := time.Now()
|
|
|
|
d := n.Truncate(duration).Add(duration).Sub(n)
|
|
|
|
t := time.NewTimer(d)
|
|
|
|
select {
|
2020-05-05 14:26:06 -04:00
|
|
|
case now := <-t.C:
|
|
|
|
return newMsg(now)
|
2020-05-05 13:36:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-11 13:01:42 -04:00
|
|
|
|
|
|
|
// Tick is a subscription that at an interval independent of the system clock
|
|
|
|
// at the given duration. That is, it begins precisely when invoked.
|
2020-05-11 22:13:34 -04:00
|
|
|
func Tick(d time.Duration, newMsg func(time.Time) Msg) Sub {
|
2020-05-11 13:01:42 -04:00
|
|
|
return func() Msg {
|
|
|
|
t := time.NewTimer(d)
|
|
|
|
select {
|
|
|
|
case now := <-t.C:
|
|
|
|
return newMsg(now)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|