-
Notifications
You must be signed in to change notification settings - Fork 338
/
observable_operator.go
2960 lines (2593 loc) · 75.1 KB
/
observable_operator.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rxgo
import (
"container/ring"
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/emirpasic/gods/trees/binaryheap"
)
// All determines whether all items emitted by an Observable meet some criteria.
func (o *ObservableImpl) All(predicate Predicate, opts ...Option) Single {
return single(o, func() operator {
return &allOperator{
predicate: predicate,
all: true,
}
}, false, false, opts...)
}
type allOperator struct {
predicate Predicate
all bool
}
func (op *allOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
if !op.predicate(item.V) {
Of(false).SendContext(ctx, dst)
op.all = false
operatorOptions.stop()
}
}
func (op *allOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *allOperator) end(ctx context.Context, dst chan<- Item) {
if op.all {
Of(true).SendContext(ctx, dst)
}
}
func (op *allOperator) gatherNext(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
if item.V == false {
Of(false).SendContext(ctx, dst)
op.all = false
operatorOptions.stop()
}
}
// AverageFloat32 calculates the average of numbers emitted by an Observable and emits the average float32.
func (o *ObservableImpl) AverageFloat32(opts ...Option) Single {
return single(o, func() operator {
return &averageFloat32Operator{}
}, false, false, opts...)
}
type averageFloat32Operator struct {
sum float32
count float32
}
func (op *averageFloat32Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: float or int, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int:
op.sum += float32(v)
op.count++
case float32:
op.sum += v
op.count++
case float64:
op.sum += float32(v)
op.count++
}
}
func (op *averageFloat32Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageFloat32Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageFloat32Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageFloat32Operator)
op.sum += v.sum
op.count += v.count
}
// AverageFloat64 calculates the average of numbers emitted by an Observable and emits the average float64.
func (o *ObservableImpl) AverageFloat64(opts ...Option) Single {
return single(o, func() operator {
return &averageFloat64Operator{}
}, false, false, opts...)
}
type averageFloat64Operator struct {
sum float64
count float64
}
func (op *averageFloat64Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: float or int, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int:
op.sum += float64(v)
op.count++
case float32:
op.sum += float64(v)
op.count++
case float64:
op.sum += v
op.count++
}
}
func (op *averageFloat64Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageFloat64Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageFloat64Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageFloat64Operator)
op.sum += v.sum
op.count += v.count
}
// AverageInt calculates the average of numbers emitted by an Observable and emits the average int.
func (o *ObservableImpl) AverageInt(opts ...Option) Single {
return single(o, func() operator {
return &averageIntOperator{}
}, false, false, opts...)
}
type averageIntOperator struct {
sum int
count int
}
func (op *averageIntOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: int, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int:
op.sum += v
op.count++
}
}
func (op *averageIntOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageIntOperator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageIntOperator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageIntOperator)
op.sum += v.sum
op.count += v.count
}
// AverageInt8 calculates the average of numbers emitted by an Observable and emits the≤ average int8.
func (o *ObservableImpl) AverageInt8(opts ...Option) Single {
return single(o, func() operator {
return &averageInt8Operator{}
}, false, false, opts...)
}
type averageInt8Operator struct {
sum int8
count int8
}
func (op *averageInt8Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: int8, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int8:
op.sum += v
op.count++
}
}
func (op *averageInt8Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageInt8Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageInt8Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageInt8Operator)
op.sum += v.sum
op.count += v.count
}
// AverageInt16 calculates the average of numbers emitted by an Observable and emits the average int16.
func (o *ObservableImpl) AverageInt16(opts ...Option) Single {
return single(o, func() operator {
return &averageInt16Operator{}
}, false, false, opts...)
}
type averageInt16Operator struct {
sum int16
count int16
}
func (op *averageInt16Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: int16, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int16:
op.sum += v
op.count++
}
}
func (op *averageInt16Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageInt16Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageInt16Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageInt16Operator)
op.sum += v.sum
op.count += v.count
}
// AverageInt32 calculates the average of numbers emitted by an Observable and emits the average int32.
func (o *ObservableImpl) AverageInt32(opts ...Option) Single {
return single(o, func() operator {
return &averageInt32Operator{}
}, false, false, opts...)
}
type averageInt32Operator struct {
sum int32
count int32
}
func (op *averageInt32Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: int32, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int32:
op.sum += v
op.count++
}
}
func (op *averageInt32Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageInt32Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageInt32Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageInt32Operator)
op.sum += v.sum
op.count += v.count
}
// AverageInt64 calculates the average of numbers emitted by an Observable and emits this average int64.
func (o *ObservableImpl) AverageInt64(opts ...Option) Single {
return single(o, func() operator {
return &averageInt64Operator{}
}, false, false, opts...)
}
type averageInt64Operator struct {
sum int64
count int64
}
func (op *averageInt64Operator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
switch v := item.V.(type) {
default:
Error(IllegalInputError{error: fmt.Sprintf("expected type: int64, got: %t", item)}).SendContext(ctx, dst)
operatorOptions.stop()
case int64:
op.sum += v
op.count++
}
}
func (op *averageInt64Operator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *averageInt64Operator) end(ctx context.Context, dst chan<- Item) {
if op.count == 0 {
Of(0).SendContext(ctx, dst)
} else {
Of(op.sum/op.count).SendContext(ctx, dst)
}
}
func (op *averageInt64Operator) gatherNext(_ context.Context, item Item, _ chan<- Item, _ operatorOptions) {
v := item.V.(*averageInt64Operator)
op.sum += v.sum
op.count += v.count
}
// BackOffRetry implements a backoff retry if a source Observable sends an error, resubscribe to it in the hopes that it will complete without error.
// Cannot be run in parallel.
func (o *ObservableImpl) BackOffRetry(backOffCfg backoff.BackOff, opts ...Option) Observable {
option := parseOptions(opts...)
next := option.buildChannel()
ctx := option.buildContext()
f := func() error {
observe := o.Observe(opts...)
for {
select {
case <-ctx.Done():
close(next)
return nil
case i, ok := <-observe:
if !ok {
return nil
}
if i.Error() {
return i.E
}
i.SendContext(ctx, next)
}
}
}
go func() {
if err := backoff.Retry(f, backOffCfg); err != nil {
Error(err).SendContext(ctx, next)
close(next)
return
}
close(next)
}()
return &ObservableImpl{
iterable: newChannelIterable(next),
}
}
// BufferWithCount returns an Observable that emits buffers of items it collects
// from the source Observable.
// The resulting Observable emits buffers every skip items, each containing a slice of count items.
// When the source Observable completes or encounters an error,
// the resulting Observable emits the current buffer and propagates
// the notification from the source Observable.
func (o *ObservableImpl) BufferWithCount(count int, opts ...Option) Observable {
if count <= 0 {
return Thrown(IllegalInputError{error: "count must be positive"})
}
return observable(o, func() operator {
return &bufferWithCountOperator{
count: count,
buffer: make([]interface{}, count),
}
}, true, false, opts...)
}
type bufferWithCountOperator struct {
count int
iCount int
buffer []interface{}
}
func (op *bufferWithCountOperator) next(ctx context.Context, item Item, dst chan<- Item, _ operatorOptions) {
op.buffer[op.iCount] = item.V
op.iCount++
if op.iCount == op.count {
Of(op.buffer).SendContext(ctx, dst)
op.iCount = 0
op.buffer = make([]interface{}, op.count)
}
}
func (op *bufferWithCountOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *bufferWithCountOperator) end(ctx context.Context, dst chan<- Item) {
if op.iCount != 0 {
Of(op.buffer[:op.iCount]).SendContext(ctx, dst)
}
}
func (op *bufferWithCountOperator) gatherNext(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
}
// BufferWithTime returns an Observable that emits buffers of items it collects from the source
// Observable. The resulting Observable starts a new buffer periodically, as determined by the
// timeshift argument. It emits each buffer after a fixed timespan, specified by the timespan argument.
// When the source Observable completes or encounters an error, the resulting Observable emits
// the current buffer and propagates the notification from the source Observable.
func (o *ObservableImpl) BufferWithTime(timespan Duration, opts ...Option) Observable {
if timespan == nil {
return Thrown(IllegalInputError{error: "timespan must no be nil"})
}
f := func(ctx context.Context, next chan Item, option Option, opts ...Option) {
observe := o.Observe(opts...)
buffer := make([]interface{}, 0)
stop := make(chan struct{})
mutex := sync.Mutex{}
checkBuffer := func() {
mutex.Lock()
if len(buffer) != 0 {
if !Of(buffer).SendContext(ctx, next) {
mutex.Unlock()
return
}
buffer = make([]interface{}, 0)
}
mutex.Unlock()
}
go func() {
defer close(next)
duration := timespan.duration()
for {
select {
case <-stop:
checkBuffer()
return
case <-ctx.Done():
return
case <-time.After(duration):
checkBuffer()
}
}
}()
for {
select {
case <-ctx.Done():
close(stop)
return
case item, ok := <-observe:
if !ok {
close(stop)
return
}
if item.Error() {
item.SendContext(ctx, next)
if option.getErrorStrategy() == StopOnError {
close(stop)
return
}
} else {
mutex.Lock()
buffer = append(buffer, item.V)
mutex.Unlock()
}
}
}
}
return customObservableOperator(f, opts...)
}
// BufferWithTimeOrCount returns an Observable that emits buffers of items it collects from the source
// Observable either from a given count or at a given time interval.
func (o *ObservableImpl) BufferWithTimeOrCount(timespan Duration, count int, opts ...Option) Observable {
if timespan == nil {
return Thrown(IllegalInputError{error: "timespan must no be nil"})
}
if count <= 0 {
return Thrown(IllegalInputError{error: "count must be positive"})
}
f := func(ctx context.Context, next chan Item, option Option, opts ...Option) {
observe := o.Observe(opts...)
buffer := make([]interface{}, 0)
stop := make(chan struct{})
send := make(chan struct{})
mutex := sync.Mutex{}
checkBuffer := func() {
mutex.Lock()
if len(buffer) != 0 {
if !Of(buffer).SendContext(ctx, next) {
mutex.Unlock()
return
}
buffer = make([]interface{}, 0)
}
mutex.Unlock()
}
go func() {
defer close(next)
duration := timespan.duration()
for {
select {
case <-send:
checkBuffer()
case <-stop:
checkBuffer()
return
case <-ctx.Done():
return
case <-time.After(duration):
checkBuffer()
}
}
}()
for {
select {
case <-ctx.Done():
return
case item, ok := <-observe:
if !ok {
close(stop)
close(send)
return
}
if item.Error() {
item.SendContext(ctx, next)
if option.getErrorStrategy() == StopOnError {
close(stop)
close(send)
return
}
} else {
mutex.Lock()
buffer = append(buffer, item.V)
if len(buffer) == count {
mutex.Unlock()
send <- struct{}{}
} else {
mutex.Unlock()
}
}
}
}
}
return customObservableOperator(f, opts...)
}
// Connect instructs a connectable Observable to begin emitting items to its subscribers.
func (o *ObservableImpl) Connect(ctx context.Context) (context.Context, Disposable) {
ctx, cancel := context.WithCancel(ctx)
o.Observe(WithContext(ctx), connect())
return ctx, Disposable(cancel)
}
// Contains determines whether an Observable emits a particular item or not.
func (o *ObservableImpl) Contains(equal Predicate, opts ...Option) Single {
return single(o, func() operator {
return &containsOperator{
equal: equal,
contains: false,
}
}, false, false, opts...)
}
type containsOperator struct {
equal Predicate
contains bool
}
func (op *containsOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
if op.equal(item.V) {
Of(true).SendContext(ctx, dst)
op.contains = true
operatorOptions.stop()
}
}
func (op *containsOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *containsOperator) end(ctx context.Context, dst chan<- Item) {
if !op.contains {
Of(false).SendContext(ctx, dst)
}
}
func (op *containsOperator) gatherNext(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
if item.V == true {
Of(true).SendContext(ctx, dst)
operatorOptions.stop()
op.contains = true
}
}
// Count counts the number of items emitted by the source Observable and emit only this value.
func (o *ObservableImpl) Count(opts ...Option) Single {
return single(o, func() operator {
return &countOperator{}
}, true, false, opts...)
}
type countOperator struct {
count int64
}
func (op *countOperator) next(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
op.count++
}
func (op *countOperator) err(_ context.Context, _ Item, _ chan<- Item, operatorOptions operatorOptions) {
op.count++
operatorOptions.stop()
}
func (op *countOperator) end(ctx context.Context, dst chan<- Item) {
Of(op.count).SendContext(ctx, dst)
}
func (op *countOperator) gatherNext(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
}
// Debounce only emits an item from an Observable if a particular timespan has passed without it emitting another item.
func (o *ObservableImpl) Debounce(timespan Duration, opts ...Option) Observable {
f := func(ctx context.Context, next chan Item, option Option, opts ...Option) {
defer close(next)
observe := o.Observe(opts...)
var latest interface{}
for {
select {
case <-ctx.Done():
return
case item, ok := <-observe:
if !ok {
return
}
if item.Error() {
if !item.SendContext(ctx, next) {
return
}
if option.getErrorStrategy() == StopOnError {
return
}
} else {
latest = item.V
}
case <-time.After(timespan.duration()):
if latest != nil {
if !Of(latest).SendContext(ctx, next) {
return
}
latest = nil
}
}
}
}
return customObservableOperator(f, opts...)
}
// DefaultIfEmpty returns an Observable that emits the items emitted by the source
// Observable or a specified default item if the source Observable is empty.
func (o *ObservableImpl) DefaultIfEmpty(defaultValue interface{}, opts ...Option) Observable {
return observable(o, func() operator {
return &defaultIfEmptyOperator{
defaultValue: defaultValue,
empty: true,
}
}, true, false, opts...)
}
type defaultIfEmptyOperator struct {
defaultValue interface{}
empty bool
}
func (op *defaultIfEmptyOperator) next(ctx context.Context, item Item, dst chan<- Item, _ operatorOptions) {
op.empty = false
item.SendContext(ctx, dst)
}
func (op *defaultIfEmptyOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *defaultIfEmptyOperator) end(ctx context.Context, dst chan<- Item) {
if op.empty {
Of(op.defaultValue).SendContext(ctx, dst)
}
}
func (op *defaultIfEmptyOperator) gatherNext(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
}
// Distinct suppresses duplicate items in the original Observable and returns
// a new Observable.
func (o *ObservableImpl) Distinct(apply Func, opts ...Option) Observable {
return observable(o, func() operator {
return &distinctOperator{
apply: apply,
keyset: make(map[interface{}]interface{}),
}
}, false, false, opts...)
}
type distinctOperator struct {
apply Func
keyset map[interface{}]interface{}
}
func (op *distinctOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
key, err := op.apply(ctx, item.V)
if err != nil {
Error(err).SendContext(ctx, dst)
operatorOptions.stop()
return
}
_, ok := op.keyset[key]
if !ok {
item.SendContext(ctx, dst)
}
op.keyset[key] = nil
}
func (op *distinctOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *distinctOperator) end(_ context.Context, _ chan<- Item) {
}
func (op *distinctOperator) gatherNext(ctx context.Context, item Item, dst chan<- Item, _ operatorOptions) {
switch item.V.(type) {
case *distinctOperator:
return
}
if _, contains := op.keyset[item.V]; !contains {
Of(item.V).SendContext(ctx, dst)
op.keyset[item.V] = nil
}
}
// DistinctUntilChanged suppresses consecutive duplicate items in the original Observable.
// Cannot be run in parallel.
func (o *ObservableImpl) DistinctUntilChanged(apply Func, opts ...Option) Observable {
return observable(o, func() operator {
return &distinctUntilChangedOperator{
apply: apply,
}
}, true, false, opts...)
}
type distinctUntilChangedOperator struct {
apply Func
current interface{}
}
func (op *distinctUntilChangedOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
key, err := op.apply(ctx, item.V)
if err != nil {
Error(err).SendContext(ctx, dst)
operatorOptions.stop()
return
}
if op.current != key {
item.SendContext(ctx, dst)
op.current = key
}
}
func (op *distinctUntilChangedOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *distinctUntilChangedOperator) end(_ context.Context, _ chan<- Item) {
}
func (op *distinctUntilChangedOperator) gatherNext(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
}
// DoOnCompleted registers a callback action that will be called once the Observable terminates.
func (o *ObservableImpl) DoOnCompleted(completedFunc CompletedFunc, opts ...Option) Disposed {
dispose := make(chan struct{})
handler := func(ctx context.Context, src <-chan Item) {
defer close(dispose)
defer completedFunc()
for {
select {
case <-ctx.Done():
return
case i, ok := <-src:
if !ok {
return
}
if i.Error() {
return
}
}
}
}
option := parseOptions(opts...)
ctx := option.buildContext()
go handler(ctx, o.Observe(opts...))
return dispose
}
// DoOnError registers a callback action that will be called if the Observable terminates abnormally.
func (o *ObservableImpl) DoOnError(errFunc ErrFunc, opts ...Option) Disposed {
dispose := make(chan struct{})
handler := func(ctx context.Context, src <-chan Item) {
defer close(dispose)
for {
select {
case <-ctx.Done():
return
case i, ok := <-src:
if !ok {
return
}
if i.Error() {
errFunc(i.E)
return
}
}
}
}
option := parseOptions(opts...)
ctx := option.buildContext()
go handler(ctx, o.Observe(opts...))
return dispose
}
// DoOnNext registers a callback action that will be called on each item emitted by the Observable.
func (o *ObservableImpl) DoOnNext(nextFunc NextFunc, opts ...Option) Disposed {
dispose := make(chan struct{})
handler := func(ctx context.Context, src <-chan Item) {
defer close(dispose)
for {
select {
case <-ctx.Done():
return
case i, ok := <-src:
if !ok {
return
}
if i.Error() {
return
}
nextFunc(i.V)
}
}
}
option := parseOptions(opts...)
ctx := option.buildContext()
go handler(ctx, o.Observe(opts...))
return dispose
}
// ElementAt emits only item n emitted by an Observable.
// Cannot be run in parallel.
func (o *ObservableImpl) ElementAt(index uint, opts ...Option) Single {
return single(o, func() operator {
return &elementAtOperator{
index: index,
}
}, true, false, opts...)
}
type elementAtOperator struct {
index uint
takeCount int
sent bool
}
func (op *elementAtOperator) next(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
if op.takeCount == int(op.index) {
item.SendContext(ctx, dst)
op.sent = true
operatorOptions.stop()
return
}
op.takeCount++
}
func (op *elementAtOperator) err(ctx context.Context, item Item, dst chan<- Item, operatorOptions operatorOptions) {
defaultErrorFuncOperator(ctx, item, dst, operatorOptions)
}
func (op *elementAtOperator) end(ctx context.Context, dst chan<- Item) {
if !op.sent {
Error(&IllegalInputError{}).SendContext(ctx, dst)
}
}
func (op *elementAtOperator) gatherNext(_ context.Context, _ Item, _ chan<- Item, _ operatorOptions) {
}
// Error returns the eventual Observable error.
// This method is blocking.
func (o *ObservableImpl) Error(opts ...Option) error {
option := parseOptions(opts...)
ctx := option.buildContext()
observe := o.iterable.Observe(opts...)
for {
select {
case <-ctx.Done():
return ctx.Err()
case item, ok := <-observe:
if !ok {
return nil
}
if item.Error() {
return item.E
}
}
}
}
// Errors returns an eventual list of Observable errors.
// This method is blocking
func (o *ObservableImpl) Errors(opts ...Option) []error {
option := parseOptions(opts...)
ctx := option.buildContext()
observe := o.iterable.Observe(opts...)
errs := make([]error, 0)
for {
select {
case <-ctx.Done():
return []error{ctx.Err()}
case item, ok := <-observe:
if !ok {
return errs
}
if item.Error() {
errs = append(errs, item.E)
}
}
}
}
// Filter emits only those items from an Observable that pass a predicate test.
func (o *ObservableImpl) Filter(apply Predicate, opts ...Option) Observable {
return observable(o, func() operator {
return &filterOperator{apply: apply}
}, false, true, opts...)