-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_test.go
More file actions
608 lines (501 loc) · 13 KB
/
example_test.go
File metadata and controls
608 lines (501 loc) · 13 KB
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
package rx_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"github.com/reactivego/rx"
)
func Example_share() {
serial := rx.NewScheduler()
shared := rx.From(1, 2, 3).Share()
ctx := rx.Background(serial)
shared.Println().Go(ctx)
shared.Println().Go(ctx)
shared.Println().Go(ctx)
serial.Wait()
// Output:
// 1
// 1
// 1
// 2
// 2
// 2
// 3
// 3
// 3
}
func Example_subject() {
serial := rx.NewScheduler()
ctx := rx.Background(serial)
// subject collects emits when there are no subscriptions active.
in, out := rx.Subject[int](0, 1)
// ignore everything before any subscriptions, except the last because buffer size is 1
in.Next(-2)
in.Next(-1)
in.Next(0)
in.Next(1)
// add a couple of subscriptions
sub1 := out.Println().Go(ctx)
sub2 := out.Println().Go(ctx)
// schedule the subsequent emits on the serial scheduler otherwise these calls
// will block because the buffer is full.
// subject will detect usage of scheduler on observable side and use it on the
// observer side to keep the data flow through the subject going.
serial.Schedule(func() {
in.Next(2)
in.Next(3)
in.Done(rx.Err)
})
serial.Wait()
fmt.Println(sub1.Wait())
fmt.Println(sub2.Wait())
// Output:
// 1
// 1
// 2
// 2
// 3
// 3
// rx
// rx
}
func Example_multicast() {
serial := rx.NewScheduler()
ctx := rx.Background(serial)
in, out := rx.Multicast[int](1)
// Ignore everything before any subscriptions, including the last!
in.Next(-2)
in.Next(-1)
in.Next(0)
in.Next(1)
// Schedule the subsequent emits in a loop. This will be the first task to
// run on the serial scheduler after the subscriptions have been added.
serial.ScheduleLoop(2, func(index int, again func(next int)) {
if index < 4 {
in.Next(index)
again(index + 1)
} else {
in.Done(rx.Err)
}
})
// Add a couple of subscriptions
sub1 := out.Println().Go(ctx)
sub2 := out.Println().Go(ctx)
// Let the scheduler run and wait for all of its scheduled tasks to finish.
serial.Wait()
fmt.Println(sub1.Wait())
fmt.Println(sub2.Wait())
// Output:
// 2
// 2
// 3
// 3
// rx
// rx
}
func Example_multicastDrop() {
serial := rx.NewScheduler()
ctx := rx.Background(serial)
const onBackpressureDrop = -1
// multicast with backpressure handling set to dropping incoming
// items that don't fit in the buffer once it has filled up.
in, out := rx.Multicast[int](1 * onBackpressureDrop)
// ignore everything before any subscriptions, including the last!
in.Next(-2)
in.Next(-1)
in.Next(0)
in.Next(1)
// add a couple of subscriptions
sub1 := out.Println().Go(ctx)
sub2 := out.Println().Go(ctx)
in.Next(2) // accepted: buffer not full
in.Next(3) // dropped: buffer full
in.Done(rx.Err) // dropped: buffer full
serial.Wait()
fmt.Println(sub1.Wait())
fmt.Println(sub2.Wait())
// Output:
// 2
// 2
// <nil>
// <nil>
}
func Example_concatAll() {
source := rx.Empty[rx.Observable[string]]()
rx.ConcatAll(source).Wait()
source = rx.Of(rx.Empty[string]())
rx.ConcatAll(source).Wait()
req := func(request string, duration time.Duration) rx.Observable[string] {
req := rx.From(request + " response")
if duration == 0 {
return req
}
return req.Delay(duration)
}
const ms = time.Millisecond
req1 := req("first", 10*ms)
req2 := req("second", 20*ms)
req3 := req("third", 0*ms)
req4 := req("fourth", 60*ms)
source = rx.From(req1).ConcatWith(rx.From(req2, req3, req4).Delay(100 * ms))
rx.ConcatAll(source).Println().Wait()
fmt.Println("OK")
// Output:
// first response
// second response
// third response
// fourth response
// OK
}
func Example_race() {
const ms = time.Millisecond
req := func(request string, duration time.Duration) rx.Observable[string] {
return rx.From(request + " response").Delay(duration)
}
req1 := req("first", 50*ms)
req2 := req("second", 10*ms)
req3 := req("third", 60*ms)
rx.Race(req1, req2, req3).Println().Wait()
err := func(text string, duration time.Duration) rx.Observable[int] {
return rx.Throw[int](errors.New(text + " error")).Delay(duration)
}
err1 := err("first", 10*ms)
err2 := err("second", 20*ms)
err3 := err("third", 30*ms)
fmt.Println(rx.Race(err1, err2, err3).Wait(rx.BackgroundGoroutine))
// Output:
// second response
// first error
}
func Example_marshal() {
type R struct {
A string `json:"a"`
B string `json:"b"`
}
b2s := func(data []byte) string { return string(data) }
rx.Map(rx.Of(R{"Hello", "World"}).Marshal(json.Marshal), b2s).Println().Wait()
// Output:
// {"a":"Hello","b":"World"}
}
func Example_elementAt() {
rx.From(0, 1, 2, 3, 4).ElementAt(2).Println().Wait()
// Output:
// 2
}
func Example_exhaustAll() {
const ms = time.Millisecond
stream := func(name string, duration time.Duration, count int) rx.Observable[string] {
return rx.Map(rx.Timer[int](0*ms, duration), func(next int) string {
return name + "-" + strconv.Itoa(next)
}).Take(count)
}
streams := []rx.Observable[string]{
stream("a", 20*ms, 3),
stream("b", 20*ms, 3),
stream("c", 20*ms, 3),
rx.Empty[string](),
}
streamofstreams := rx.Map(rx.Timer[int](20*ms, 30*ms, 250*ms, 100*ms).Take(4), func(next int) rx.Observable[string] {
return streams[next]
})
err := rx.ExhaustAll(streamofstreams).Println().Wait()
if err == nil {
fmt.Println("success")
}
// Output:
// a-0
// a-1
// a-2
// c-0
// c-1
// c-2
// success
}
func Example_bufferCount() {
source := rx.From(0, 1, 2, 3)
fmt.Println("BufferCount(From(0, 1, 2, 3), 2, 1)")
rx.BufferCount(source, 2, 1).Println().Wait()
fmt.Println("BufferCount(From(0, 1, 2, 3), 2, 2)")
rx.BufferCount(source, 2, 2).Println().Wait()
fmt.Println("BufferCount(From(0, 1, 2, 3), 2, 3)")
rx.BufferCount(source, 2, 3).Println().Wait()
fmt.Println("BufferCount(From(0, 1, 2, 3), 3, 2)")
rx.BufferCount(source, 3, 2).Println().Wait()
fmt.Println("BufferCount(From(0, 1, 2, 3), 6, 6)")
rx.BufferCount(source, 6, 6).Println().Wait()
fmt.Println("BufferCount(From(0, 1, 2, 3), 2, 0)")
rx.BufferCount(source, 2, 0).Println().Wait()
// Output:
// BufferCount(From(0, 1, 2, 3), 2, 1)
// [0 1]
// [1 2]
// [2 3]
// [3]
// BufferCount(From(0, 1, 2, 3), 2, 2)
// [0 1]
// [2 3]
// BufferCount(From(0, 1, 2, 3), 2, 3)
// [0 1]
// [3]
// BufferCount(From(0, 1, 2, 3), 3, 2)
// [0 1 2]
// [2 3]
// BufferCount(From(0, 1, 2, 3), 6, 6)
// [0 1 2 3]
// BufferCount(From(0, 1, 2, 3), 2, 0)
// [0 1]
}
func Example_switchAll() {
const ms = time.Millisecond
// Emit 0,1,2,3 with 42ms in between
interval42x4 := rx.Interval[int](42 * ms).Take(4)
// Emit 0,1,2,3 with 16ms in between
interval16x4 := rx.Interval[int](16 * ms).Take(4)
overlapping := rx.Map(interval42x4, func(next int) rx.Observable[int] {
return interval16x4
})
err := rx.SwitchAll(overlapping).Println().Wait(rx.BackgroundGoroutine)
if err == nil {
fmt.Println("success")
}
// Output:
// 0
// 1
// 0
// 1
// 0
// 1
// 0
// 1
// 2
// 3
// success
}
func Example_switchMap() {
const ms = time.Millisecond
webreq := func(request string, duration time.Duration) rx.Observable[string] {
return rx.From(request + " result").Delay(duration)
}
first := webreq("first", 50*ms)
second := webreq("second", 10*ms)
latest := webreq("latest", 50*ms)
switchmap := rx.SwitchMap(rx.Interval[int](20*ms).Take(3), func(i int) rx.Observable[string] {
switch i {
case 0:
return first
case 1:
return second
case 2:
return latest
default:
return rx.Empty[string]()
}
})
err := switchmap.Println().Wait()
if err == nil {
fmt.Println("success")
}
// Output:
// second result
// latest result
// success
}
func Example_retry() {
var first error = rx.Err
a := rx.Create(func(index int) (next int, err error, done bool) {
if index < 3 {
return index, nil, false
}
err, first = first, nil
return 0, err, true
})
err := a.Retry().Println().Wait()
fmt.Println(first == nil)
fmt.Println(err)
// Output:
// 0
// 1
// 2
// 0
// 1
// 2
// true
// <nil>
}
func Example_count() {
source := rx.From(1, 2, 3, 4, 5)
count := source.Count()
count.Println().Wait()
emptySource := rx.Empty[int]()
emptyCount := emptySource.Count()
emptyCount.Println().Wait()
fmt.Println("OK")
// Output:
// 5
// 0
// OK
}
func Example_values() {
source := rx.From(1, 3, 5)
// Why choose the Goroutine concurrent scheduler?
// An observable can actually be at the root of a tree
// of separately running observables that have their
// responses merged. The Goroutine scheduler allows
// these observables to run concurrently.
// run the observable on 1 or more goroutines
for i := range source.Values(rx.BackgroundGoroutine) {
// This is called from a newly created goroutine
fmt.Println(i)
}
// run the observable on the current goroutine
for i := range source.Values() {
fmt.Println(i)
}
fmt.Println("OK")
// Output:
// 1
// 3
// 5
// 1
// 3
// 5
// OK
}
func Example_all() {
source := rx.From("ZERO", "ONE", "TWO")
for next, err := range source.All() {
if err != nil {
fmt.Println("Unexpected error:", err)
}
fmt.Println(next.First, next.Second)
}
fmt.Println("OK")
// Output:
// 0 ZERO
// 1 ONE
// 2 TWO
// OK
}
func Example_skip() {
rx.From(1, 2, 3, 4, 5).Skip(2).Println().Wait()
// Output:
// 3
// 4
// 5
}
func Example_autoConnect() {
// Create a multicaster hot observable that will emit every 100 milliseconds
hot := rx.Interval[int](100 * time.Millisecond).Take(10).Publish()
hotsub := hot.Connect(rx.BackgroundGoroutine)
defer hotsub.Unsubscribe()
fmt.Println("Hot observable created and emitting 0,1,2,3,4,5,6 ...")
// Publish the hot observable again but only Connect to it when 2
// subscribers have connected.
source := hot.Take(5).Publish().AutoConnect(2)
// First subscriber
sub1 := source.Printf("Subscriber 1: %d\n").Go()
fmt.Println("First subscriber connected, waiting a bit...")
// Wait a bit, nothing will emit yet
time.Sleep(525 * time.Millisecond)
fmt.Println("Second subscriber connecting, emissions begin!")
// Second subscriber triggers the connection
sub2 := source.Printf("Subscriber 2: %d\n").Go()
// Wait for emissions to complete
hotsub.Wait()
sub1.Wait()
sub2.Wait()
// Unordered output:
// Hot observable created and emitting 0,1,2,3,4,5,6 ...
// First subscriber connected, waiting a bit...
// Second subscriber connecting, emissions begin!
// Subscriber 1: 5
// Subscriber 2: 5
// Subscriber 1: 6
// Subscriber 2: 6
// Subscriber 1: 7
// Subscriber 2: 7
// Subscriber 1: 8
// Subscriber 2: 8
// Subscriber 1: 9
// Subscriber 2: 9
}
func Example_mergeMap() {
source := rx.From("https://reactivego.io", "https://github.com/reactivego")
merged := rx.MergeMap(source, func(next string) rx.Observable[string] {
fakeFetchData := rx.Of(fmt.Sprintf("content of %q", next))
return fakeFetchData
})
merged.Println().Go(context.Background()).Wait()
// Output:
// content of "https://reactivego.io"
// content of "https://github.com/reactivego"
}
func Example_mergeMapSubject() {
source := rx.From("https://google.com", "https://reactivego.io", "https://github.com/reactivego")
merged := rx.MergeMap(source, func(next string) rx.Observable[string] {
fakeFetchData := rx.Of(fmt.Sprintf("content of %q", next))
return fakeFetchData
})
// subject remembers last 2 emits by the observer for an hour.
observer, subject := rx.Subject[string](time.Hour, 2)
// First subscriber starts before merged completes, so sees all emits live
wait := subject.Println().Go()
merged.Tap(observer).Go().Wait()
wait.Wait()
// Sees only last 2 emits
subject.Println().Go().Wait()
// Sees only last 2 emits
subject.Println().Go().Wait()
// Output:
// content of "https://google.com"
// content of "https://reactivego.io"
// content of "https://github.com/reactivego"
// content of "https://reactivego.io"
// content of "https://github.com/reactivego"
// content of "https://reactivego.io"
// content of "https://github.com/reactivego"
}
func Example_commandPattern() {
type Data struct {
Id string
Val int
}
// collect is an example of a long running observable producing data.
collect := func(id string) rx.Observable[Data] {
take5 := rx.Interval[int](100 * time.Millisecond).Take(5)
// use rx.Defer to have a scope per subscription available.
return rx.Defer(func() rx.Observable[Data] {
// this scope is for storing data per subscription
// for example say you want to support retries,
// then this scope will be active per retry.
return rx.Map(take5, func(val int) Data {
return Data{Id: id, Val: val}
})
})
}
// setup a channel to push commands into, where a command is an rx.Observable[Data]
commands := make(chan rx.Observable[Data], 2)
// now user MergeAll to run all commands in parallel and merge their output
sub := rx.MergeAll(rx.Recv(commands)).Println().Go()
// launch a bunch of commands.
commands <- collect("hello")
commands <- collect("world")
// We need to make sure the command channel is closed.
close(commands)
// then wait for everything to play out
sub.Wait()
// Unordered output:
// {hello 0}
// {world 0}
// {hello 1}
// {world 1}
// {hello 2}
// {world 2}
// {hello 3}
// {world 3}
// {hello 4}
// {world 4}
}