-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsampletime.go
48 lines (46 loc) · 1.1 KB
/
sampletime.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
package rx
import (
"sync"
"time"
)
// SampleTime emits the most recent item emitted by an Observable within periodic time intervals.
func (observable Observable[T]) SampleTime(window time.Duration) Observable[T] {
return func(observe Observer[T], scheduler Scheduler, subscriber Subscriber) {
var sample struct {
sync.Mutex
at time.Time
next T
done bool
}
sampler := scheduler.ScheduleFutureRecursive(window, func(self func(time.Duration)) {
if subscriber.Subscribed() {
sample.Lock()
if !sample.done {
begin := scheduler.Now().Add(-window)
if !sample.at.Before(begin) {
observe(sample.next, nil, false)
}
if subscriber.Subscribed() {
self(window)
}
}
sample.Unlock()
}
})
subscriber.OnUnsubscribe(sampler.Cancel)
observer := func(next T, err error, done bool) {
if subscriber.Subscribed() {
sample.Lock()
sample.at = scheduler.Now()
sample.next = next
sample.done = done
sample.Unlock()
if done {
var zero T
observe(zero, err, true)
}
}
}
observable(observer, scheduler, subscriber)
}
}