-
Notifications
You must be signed in to change notification settings - Fork 1
/
observable.go
473 lines (405 loc) · 9.65 KB
/
observable.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package daisychain
import (
"fmt"
"sync"
"time"
)
var Trace bool = false
var TRACE = func(prefix string, ev Event) {
//set var Trace=true
}
func trace() {
if !Trace {
return
}
var seq int
TRACE = func(prefix string, ev Event) {
fmt.Printf("%s: %d -> %s, %#v, (type:%T)\n", time.Now(), seq, prefix, ev, ev)
seq++
}
}
type Event interface{}
// CompleteEvent indicates that no more Events will be send.
type CompleteEvent struct {
Event
}
// Complete creates a new Event of type CompleteEvent.
func Complete() Event {
return CompleteEvent{}
}
// IsCompleteEvent returns true if ev is a CompleteEvent.
func IsCompleteEvent(ev Event) bool {
_, isCompleteEvent := ev.(CompleteEvent)
return isCompleteEvent
}
// IsErrorEvent returns true if ev is a CompleteEvent.
func IsErrorEvent(ev Event) bool {
_, isErrorEvent := ev.(ErrorEvent)
return isErrorEvent
}
// ErrorEvent indicates an Error.
type ErrorEvent struct {
Event
msg string
}
// Error creates a new Event of type ErrorEvent.
func Error(msg string) Event {
return ErrorEvent{msg: msg}
}
type Observable interface {
Observe(Observer)
}
type ObservableFunc func(Observer)
// Observe method implements the Observable interface on the fly.
func (o ObservableFunc) Observe(obs Observer) {
o(obs)
}
type Observer interface {
Next(ev Event)
}
type ObserverFunc func(Event)
// Next method implements the Observer interface on the fly.
func (o ObserverFunc) Next(ev Event) {
o(ev)
}
type Operator func(Observable) Observable
type MapFunc func(Event) Event
func Map(mapfn MapFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
next = mapfn(cur)
obs.Next(next)
}
return next
}, "Map()", nil)
}
type FlatMapFunc func(ev Event) Observable
func FlatMap(flatmapfn FlatMapFunc) Operator {
var wg sync.WaitGroup
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
TRACE("FlatMap()", "WAITING...")
wg.Wait()
obs.Next(cur)
} else {
TRACE("FlatMap()", "SPAWNING")
wg.Add(1)
o := flatmapfn(cur)
onNext := func(ev Event) {
next = ev
obs.Next(next)
}
onEvent := func(ev Event) {
TRACE("FlatMap()", "DONE")
wg.Done()
}
Subscribe(o, onNext, onEvent, onEvent)
}
return next
}, "FlatMap()", nil)
}
type ReduceFunc func(left, right Event) Event
func Scan(reducefn ReduceFunc, init Event) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
next = reducefn(last, cur)
obs.Next(next)
}
return next
}, "Scan()", init)
}
func Reduce(reducefn ReduceFunc, init Event) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
var next Event
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(last)
obs.Next(cur)
} else {
next = reducefn(last, cur)
}
return next
}, "Reduce()", init)
}
func Skip(n int) Operator {
var count int
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if count == n {
obs.Next(cur)
} else {
count += 1
}
}
return cur
}, "Skip()", nil)
}
func Take(n int) Operator {
var count int
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if count < n {
obs.Next(cur)
count += 1
}
}
return cur
}, "Take()", nil)
}
type FilterFunc func(Event) bool
func Filter(filterfn FilterFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
if ok := filterfn(cur); ok {
obs.Next(cur)
}
}
return cur
}, "Filter()", nil)
}
// ToVector collects all events until Complete and the returns an Event
// that can be cast to []Event containing all collected events.
func ToVector() Operator {
var events []Event
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(events)
obs.Next(cur)
} else {
events = append(events, cur)
}
return cur
}, "ToVector()", nil)
}
type KeyFunc func(ev Event) string
// ToMap collects all events until Complete and the returns an Event
// that can be cast to map[string][]Event containing all collected events
// grouped by the result of KeyFunc.
func ToMap(keyfn KeyFunc) Operator {
events := make(map[string][]Event)
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(events)
obs.Next(cur)
} else {
key := keyfn(cur)
events[key] = append(events[key], cur)
}
return cur
}, "ToMap()", nil)
}
// Distinct emits each event only the first time it occurs based on the
// result of KeyFunc. Two events are equal, if KeyFunc returns the same
// result for them.
func Distinct(keyfn KeyFunc) Operator {
seen := make(map[string]struct{})
return OperatorFunc(func(obs Observer, cur, last Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(cur)
} else {
key := keyfn(cur)
if _, exists := seen[key]; !exists {
obs.Next(cur)
seen[key] = struct{}{}
}
}
return cur
}, "Distinct()", nil)
}
func Count() Operator {
var counter int64
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
if IsCompleteEvent(cur) || IsErrorEvent(cur) {
obs.Next(counter)
obs.Next(cur)
} else {
counter++
}
return cur
}, "Count()", nil)
}
type ZipFunc func(evs ...Event) Event
// Zip works ONLY, if all event streams emit the same number of events
func Zip(zipfunc ZipFunc, oo ...Observable) Operator {
var receiver []chan Event
var onNext, onEnd func(ev Event)
for _, o := range oo {
output := make(chan Event)
onNext = func(ev Event) {
output <- ev
}
onEnd = func(ev Event) {
//output <- ev //FIXME(SR): Always post last ev?
close(output)
}
receiver = append(receiver, output)
Subscribe(o, onNext, onEnd, onEnd)
}
realize := func(receiver ...chan Event) []Event {
var result []Event
for _, r := range receiver {
result = append(result, func() Event { return <-r }())
}
return result
}
return OperatorFunc(func(obs Observer, cur, _ Event) Event {
head := []Event{cur}
tail := realize(receiver...)
args := append(head, tail...)
for _, a := range args {
if IsCompleteEvent(a) || IsErrorEvent(a) {
obs.Next(Complete())
return cur
}
}
obs.Next(zipfunc(args...))
return cur
}, "Zip()", nil)
}
type DebugFunc func(obs Observer, cur, last Event)
func Debug(debugfn DebugFunc) Operator {
return OperatorFunc(func(obs Observer, cur, last Event) Event {
debugfn(obs, cur, last)
obs.Next(cur)
return cur
}, "DEBUG()", nil)
}
type BodyFunc func(obs Observer, cur, last Event) Event
func OperatorFunc(do BodyFunc, name string, init Event) Operator {
return func(o Observable) Observable {
return ObservableFunc(func(obs Observer) {
input := make(chan Event, 10)
//FIXME(SR): Buffering is needed to make Zip() work...
//input := make(chan Event)
msg := fmt.Sprintf("Opening channel for %s", name)
TRACE(msg, input)
go func() {
last := init
TRACE("Starting", name)
for ev := range input {
last = do(obs, ev, last)
TRACE(name, last)
}
TRACE("Closing", name)
}()
o.Observe(ObserverFunc(func(ev Event) {
TRACE("EVENT", ev)
input <- ev
//if IsCompleteEvent(ev) || IsErrorEvent(ev) {
if IsCompleteEvent(ev) { //FIXME(SR): Is there always a complete after an error?
TRACE("Closing channel", input)
close(input)
}
}))
})
}
}
func closeIfOpen(input chan Event) {
if input != nil {
close(input)
}
}
func callIfNotNil(onEvent ObserverFunc, ev Event) {
if onEvent != nil {
onEvent(ev)
}
}
func Subscribe(o Observable, onNext, onError, onComplete ObserverFunc) {
trace()
var last Event
o.Observe(ObserverFunc(func(ev Event) {
TRACE("Subscribe:", ev)
switch ev.(type) {
case CompleteEvent:
callIfNotNil(onComplete, last)
case ErrorEvent:
callIfNotNil(onError, ev)
default:
last = ev
callIfNotNil(onNext, ev)
}
}))
}
func SubscribeAndWait(o Observable, onNext, onError, onComplete ObserverFunc) {
trace()
var wg sync.WaitGroup
var last Event
wg.Add(1)
o.Observe(ObserverFunc(func(ev Event) {
TRACE("SubscribeAndWait:", ev)
switch ev.(type) {
case CompleteEvent:
callIfNotNil(onComplete, last)
wg.Done()
case ErrorEvent:
callIfNotNil(onError, ev)
default:
last = ev
callIfNotNil(onNext, ev)
}
}))
wg.Wait()
}
func Cache(o Observable) Observable {
var evts []Event
oo := Create(
o,
ToVector(),
)
onComplete := func(ev Event) {
evts = ev.([]Event)
}
SubscribeAndWait(oo, nil, nil, onComplete)
return ObservableFunc(func(obs Observer) {
evts := evts
for _, ev := range evts {
obs.Next(ev)
}
obs.Next(Complete())
})
}
func build(o Observable, ops ...Operator) Observable {
var chained Observable = o
for _, op := range ops {
chained = op(chained)
}
return chained
}
func Create(o Observable, ops ...Operator) Observable {
TRACE("Create", o)
return build(o, ops...)
}
func Just(evts ...Event) Observable {
return ObservableFunc(func(obs Observer) {
for _, ev := range evts {
TRACE("Just", ev)
obs.Next(ev)
}
obs.Next(Complete())
})
}
func From(evts ...Event) Observable {
return ObservableFunc(func(obs Observer) {
for _, ev := range evts {
TRACE("From", ev)
obs.Next(ev)
}
})
}
func Empty() Observable {
return ObservableFunc(func(obs Observer) {
obs.Next(Complete())
})
}