-
Notifications
You must be signed in to change notification settings - Fork 1
/
sources.go
238 lines (209 loc) · 5.4 KB
/
sources.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// SPDX-License-Identifier: Apache-2.0
// Copyright 2022 Jussi Maki
package stream
import (
"context"
"fmt"
"sync"
"time"
)
//
// Sources, e.g. operators that create new observables.
//
// Just creates an observable with a single item.
func Just[T any](item T) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
if err := ctx.Err(); err != nil {
return err
}
return next(item)
})
}
// Stuck creates an observable that never emits anything and
// just waits for the context to be cancelled.
// Mainly meant for testing.
func Stuck[T any]() Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
<-ctx.Done()
return ctx.Err()
})
}
// Error creates an observable that fails immediately with given error.
func Error[T any](err error) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
return err
})
}
// Empty creates an empty observable that completes immediately.
func Empty[T any]() Observable[T] {
return Error[T](nil)
}
// FromSlice converts a slice into an Observable.
func FromSlice[T any](items []T) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
for _, item := range items {
if ctx.Err() != nil {
return ctx.Err()
}
if err := next(item); err != nil {
return err
}
}
return nil
})
}
// FromAnySlice converts a slice of 'any' into an Observable of specified type.
func FromAnySlice[T any](items []any) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
for _, anyItem := range items {
if ctx.Err() != nil {
return ctx.Err()
}
item, ok := anyItem.(T)
if !ok {
var target T
return fmt.Errorf("FromAnySlice[%T]: %T not castable to target type", target, anyItem)
}
if err := next(item); err != nil {
return err
}
}
return nil
})
}
// FromChannel creates an observable from a channel. The channel is consumed
// by the first observer.
func FromChannel[T any](in <-chan T) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
// TODO: we're blocking on receive and only handling
// context cancellation after it. Issue here is that
// if we just do for+select we don't know if 'in' is
// closed and should stop.
for v := range in {
if ctx.Err() != nil {
return ctx.Err()
}
if err := next(v); err != nil {
return err
}
}
return nil
})
}
func FromFunction[T any](f func() T) Observable[T] {
return FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
if err := ctx.Err(); err != nil {
return err
}
return next(f())
})
}
// Interval emits an increasing counter value every 'interval' period.
func Interval(interval time.Duration) Observable[int] {
return FuncObservable[int](
func(ctx context.Context, next func(int) error) error {
ticker := time.NewTicker(interval)
defer ticker.Stop()
done := ctx.Done()
for i := 0; ; i++ {
select {
case <-done:
return ctx.Err()
case <-ticker.C:
if err := next(i); err != nil {
return err
}
}
}
})
}
// Range creates an observable that emits integers in range from...to-1.
func Range(from, to int) Observable[int] {
return FuncObservable[int](
func(ctx context.Context, next func(int) error) error {
for i := from; i < to; i++ {
if ctx.Err() != nil {
return ctx.Err()
}
if err := next(i); err != nil {
return err
}
}
return nil
})
}
// Deferred creates an observable that allows subscribing, but
// waits for the real observable to be provided later.
func Deferred[T any]() (src Observable[T], start func(Observable[T])) {
var (
mu sync.Mutex
cond = sync.NewCond(&mu)
realSrc Observable[T]
)
src = FuncObservable[T](
func(ctx context.Context, next func(T) error) error {
mu.Lock()
defer mu.Unlock()
for realSrc == nil { cond.Wait() }
return realSrc.Observe(ctx, next)
})
start = func(src Observable[T]) {
mu.Lock()
defer mu.Unlock()
realSrc = src
cond.Broadcast()
}
return
}
type observableValue[T any] struct {
mu sync.RWMutex
value T
updates chan<- T
closed bool
}
func (ov *observableValue[T]) Get() T {
ov.mu.RLock()
defer ov.mu.RUnlock()
return ov.value
}
func (ov *observableValue[T]) Update(f func(*T)) {
ov.mu.Lock()
defer ov.mu.Unlock()
if ov.closed { panic("ObservableValue is closed") }
f(&ov.value)
ov.updates <- ov.value
}
func (ov *observableValue[T]) Close() {
ov.mu.Lock()
defer ov.mu.Unlock()
ov.closed = true
close(ov.updates)
}
type ObservableValue[T any] interface {
// Get retrieves the latest value
Get() T
// Update updates the value with a function that modifies
// it. Observers of the value are notified of the new value.
// Panics if called after Close().
Update(f func(*T))
// Close the value. Any observers to this value are completed.
Close()
}
func NewObservableValue[T any](ctx context.Context, init T) (ObservableValue[T], Observable[T], error) {
updates := make(chan T)
// Wrap the updates channel into a multicast source that emits
// the last seen value when subscribing.
src, connect := Multicast(
MulticastParams{BufferSize: 16, EmitLatest: true},
FromChannel(updates))
go connect(ctx)
ov := &observableValue[T]{value: init, updates: updates}
return ov, src, nil
}