-
Notifications
You must be signed in to change notification settings - Fork 11
/
interval.go
58 lines (45 loc) · 1.02 KB
/
interval.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package co
import (
"time"
syncx "go.tempura.ink/co/internal/syncx"
)
type AsyncInterval[R any] struct {
*asyncSequence[R]
period int
ended syncx.AtomicBool
}
func Interval(period int) *AsyncInterval[int] {
a := &AsyncInterval[int]{
period: period,
}
a.asyncSequence = NewAsyncSequence[int](a)
return a
}
func (a *AsyncInterval[R]) Complete() *AsyncInterval[R] {
a.ended.Set(true)
return a
}
func (a *AsyncInterval[R]) iterator() Iterator[R] {
it := &asyncIntervalIterator[R]{
AsyncInterval: a,
timer: time.NewTicker(time.Duration(a.period) * time.Millisecond),
}
it.asyncSequenceIterator = NewAsyncSequenceIterator[R](it)
return it
}
type asyncIntervalIterator[R any] struct {
*asyncSequenceIterator[R]
*AsyncInterval[R]
timer *time.Ticker
}
func (it *asyncIntervalIterator[R]) cleanUp() *Optional[R] {
it.timer.Stop()
return NewOptionalEmpty[R]()
}
func (it *asyncIntervalIterator[R]) next() *Optional[R] {
if it.ended.Get() {
return it.cleanUp()
}
<-it.timer.C
return OptionalOf(*new(R))
}