-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathRxScalaDemo.scala
More file actions
1931 lines (1664 loc) · 65.8 KB
/
RxScalaDemo.scala
File metadata and controls
1931 lines (1664 loc) · 65.8 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
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
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import rx.lang.scala.subjects.SerializedSubject
import scala.concurrent.Await
import scala.collection.immutable.HashMap
import scala.collection.mutable
import scala.concurrent.duration.Duration
import scala.concurrent.duration.DurationInt
import scala.concurrent.duration.DurationLong
import scala.concurrent.ExecutionContext
import scala.language.postfixOps
import scala.language.implicitConversions
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.assertFalse
import org.junit.Ignore
import org.junit.Test
import org.scalatestplus.junit.JUnitSuite
import rx.lang.scala._
import rx.lang.scala.observables.{AsyncOnSubscribe, SyncOnSubscribe}
import rx.lang.scala.schedulers._
/**
* Demo how the different operators can be used. In Eclipse, you can right-click
* a test and choose "Run As" > "Scala JUnit Test".
*
* For each operator added to Observable.java, we add a little usage demo here.
* It does not need to test the functionality (that's already done by the tests in
* RxJava core), but it should demonstrate how it can be used, to make sure that
* the method signature makes sense.
*/
@Ignore // Since this doesn't do automatic testing, don't increase build time unnecessarily
class RxScalaDemo extends JUnitSuite {
@Test def subscribeExample(): Unit = {
val o = Observable.just(1, 2, 3)
// Generally, we have two methods, `subscribe` and `foreach`, to listen to the messages from an Observable.
// `foreach` is just an alias to `subscribe`.
o.subscribe(
n => println(n),
e => e.printStackTrace(),
() => println("done")
)
o.foreach(
n => println(n),
e => e.printStackTrace(),
() => println("done")
)
// For-comprehension is also an alternative, if you are only interested in `onNext`
for (i <- o) {
println(i)
}
}
@Test def intervalExample(): Unit = {
val o = Observable.interval(200 millis).take(5)
o.subscribe(n => println("n = " + n))
// need to wait here because otherwise JUnit kills the thread created by interval()
waitFor(o)
println("done")
}
def msTicks(start: Long, step: Long): Observable[Long] = {
// will be easier once we have Observable.generate method
Observable.interval(step millis) map (_ * step + start)
}
def prefixedTicks(start: Long, step: Long, prefix: String): Observable[String] = {
msTicks(start, step).map(prefix + _)
}
@Test def testTicks(): Unit = {
val o = prefixedTicks(5000, 500, "t = ").take(5)
o.subscribe(output(_))
waitFor(o)
}
@Test def testSwitch(): Unit = {
// We do not have ultimate precision: Sometimes, 747 gets through, sometimes not
val o = Observable.interval(1000 millis).map(n => prefixedTicks(0, 249, s"Observable#$n: "))
.switch.take(16)
o.subscribe(output(_))
waitFor(o)
}
@Test def testSwitchOnObservableOfInt(): Unit = {
// Correctly rejected with error
// "Cannot prove that Observable[Int] <:< Observable[Observable[U]]"
// val o = Observable(1, 2).switch
}
@Test def testObservableComparison(): Unit = {
val first = Observable.from(List(10, 11, 12))
val second = Observable.from(List(10, 11, 12))
val b = (first zip second) forall { case (a, b) => a == b }
assertTrue(b.toBlocking.single)
}
@Test def testObservableComparisonWithForComprehension(): Unit = {
val first = Observable.from(List(10, 11, 12))
val second = Observable.from(List(10, 11, 12))
val booleans = for ((n1, n2) <- (first zip second)) yield (n1 == n2)
val b1 = booleans.forall(identity)
assertTrue(b1.toBlocking.single)
}
@Test def testStartWithIsUnnecessary(): Unit = {
val before = List(-2, -1, 0).toObservable
val source = List(1, 2, 3).toObservable
println((before ++ source).toBlocking.toList)
}
@Test def mergeTwoExample(): Unit = {
val slowNumbers = Observable.interval(400 millis).take(5).map("slow " + _)
val fastNumbers = Observable.interval(200 millis).take(10).map("fast " + _)
val o = (slowNumbers merge fastNumbers)
o.subscribe(output(_))
waitFor(o)
}
def myInterval(period: Long): Observable[String] = {
Observable.interval(period.millis).map(n => s"Obs-$period emits $n")
}
@Test def flattenManyExample(): Unit = {
val o = Observable.interval(500 millis).map(n => myInterval((n+1)*100))
val stopper = Observable.interval(5 seconds)
o.flatten.takeUntil(stopper).toBlocking.foreach(println(_))
}
@Test def flattenSomeExample(): Unit = {
// To merge some observables which are all known already:
List(
Observable.interval(200 millis),
Observable.interval(400 millis),
Observable.interval(800 millis)
).toObservable.flatten.take(12).toBlocking.foreach(println(_))
}
@Test def flattenExample(): Unit = {
List(
Observable.interval(200 millis).map(_ => 1).take(5),
Observable.interval(200 millis).map(_ => 2).take(5),
Observable.interval(200 millis).map(_ => 3).take(5),
Observable.interval(200 millis).map(_ => 4).take(5)
).toObservable.flatten.toBlocking.foreach(println(_))
}
@Test def flattenExample2(): Unit = {
List(
Observable.interval(200 millis).map(_ => 1).take(5),
Observable.interval(200 millis).map(_ => 2).take(5),
Observable.interval(200 millis).map(_ => 3).take(5),
Observable.interval(200 millis).map(_ => 4).take(5)
).toObservable.flatten(2).toBlocking.foreach(println(_))
}
@Test def tumblingBufferExample(): Unit = {
val o = Observable.from(1 to 18)
o.tumblingBuffer(5).subscribe((l: Seq[Int]) => println(l.mkString("[", ", ", "]")))
}
@Test def tumblingBufferExample2(): Unit = {
val o = Observable.from(1 to 18).zip(Observable.interval(100 millis)).map(_._1)
val boundary = Observable.interval(500 millis)
o.tumblingBuffer(boundary).toBlocking.foreach((l: Seq[Int]) => println(l.mkString("[", ", ", "]")))
}
@Test def slidingBufferExample(): Unit = {
val o = Observable.from(1 to 18).slidingBuffer(4, 2)
o.subscribe(println(_))
}
@Test def slidingBufferExample2(): Unit = {
val open = Observable.interval(300 millis)
val closing = Observable.interval(600 millis)
val o = Observable.interval(100 millis).take(20).slidingBuffer(open)(_ => closing)
o.zipWithIndex.toBlocking.foreach {
case (seq, i) => println(s"Observable#$i emits $seq")
}
}
@Test def slidingBufferExample3(): Unit = {
val o = Observable.from(1 to 18).zip(Observable.interval(100 millis)).map(_._1)
o.slidingBuffer(500 millis, 200 millis).toBlocking.foreach((l: Seq[Int]) => println(l.mkString("[", ", ", "]")))
}
@Test def tumblingExample(): Unit = {
(for ((o, i) <- Observable.from(1 to 18).tumbling(5).zipWithIndex; n <- o)
yield s"Observable#$i emits $n"
).subscribe(output(_))
}
@Test def tumblingExample2(): Unit = {
val windowObservable = Observable.interval(500 millis)
val o = Observable.from(1 to 20).zip(Observable.interval(100 millis)).map(_._1)
(for ((o, i) <- o.tumbling(windowObservable).zipWithIndex; n <- o)
yield s"Observable#$i emits $n"
).toBlocking.foreach(println)
}
@Test def slidingExample(): Unit = {
val o = Observable.from(1 to 18).sliding(4, 2)
(for ((o, i) <- o.zipWithIndex;
n <- o)
yield s"Observable#$i emits $n"
).toBlocking.foreach(println)
}
@Test def slidingExample2(): Unit = {
val o = Observable.interval(100 millis).take(20).sliding(500 millis, 200 millis)
(for ((o, i) <- o.zipWithIndex;
n <- o)
yield s"Observable#$i emits $n"
).toBlocking.foreach(println)
}
@Test def slidingExample3(): Unit = {
val open = Observable.interval(300 millis)
val closing = Observable.interval(600 millis)
val o = Observable.interval(100 millis).take(20).sliding(open)(_ => closing)
(for ((o, i) <- o.zipWithIndex;
n <- o)
yield s"Observable#$i emits $n"
).toBlocking.foreach(println)
}
@Test def testReduce(): Unit = {
assertEquals(10, List(1, 2, 3, 4).toObservable.reduce(_ + _).toBlocking.single)
}
@Test def testForeach(): Unit = {
val numbers = Observable.interval(200 millis).take(3)
// foreach is not available on normal Observables:
// for (n <- numbers) println(n+10)
// but on BlockingObservable, it is:
for (n <- numbers.toBlocking) println(n+10)
}
@Test def testForComprehension(): Unit = {
val observables = List(List(1, 2, 3).toObservable, List(10, 20, 30).toObservable).toObservable
val squares = (for (o <- observables; i <- o if i % 2 == 0) yield i*i)
assertEquals(squares.toBlocking.toList, List(4, 100, 400, 900))
}
@Test def nextExample(): Unit = {
val o = Observable.interval(100 millis).take(20)
for(i <- o.toBlocking.next) {
println(i)
Thread.sleep(200)
}
}
@Test def latestExample(): Unit = {
val o = Observable.interval(100 millis).take(20)
for(i <- o.toBlocking.latest) {
println(i)
Thread.sleep(200)
}
}
@Test def toFutureExample(): Unit = {
val o = Observable.interval(500 millis).take(1)
val r = Await.result(o.toBlocking.toFuture, 2 seconds)
println(r)
}
@Test def testTwoSubscriptionsToOneInterval(): Unit = {
val o = Observable.interval(100 millis).take(8)
o.subscribe(
i => println(s"${i}a (on thread #${Thread.currentThread().getId})")
)
o.subscribe(
i => println(s"${i}b (on thread #${Thread.currentThread().getId})")
)
waitFor(o)
}
@Test def schedulersExample(): Unit = {
val o = Observable.interval(100 millis).take(8)
o.observeOn(NewThreadScheduler()).subscribe(
i => println(s"${i}a (on thread #${Thread.currentThread().getId})")
)
o.observeOn(NewThreadScheduler()).subscribe(
i => println(s"${i}b (on thread #${Thread.currentThread().getId})")
)
waitFor(o)
}
@Test def testGroupByThenFlatMap(): Unit = {
val m = List(1, 2, 3, 4).toObservable
val g = m.groupBy(i => i % 2)
val t = g.flatMap((p: (Int, Observable[Int])) => p._2)
assertEquals(List(1, 2, 3, 4), t.toBlocking.toList)
}
@Test def testGroupByThenFlatMapByForComprehension(): Unit = {
val m = List(1, 2, 3, 4).toObservable
val g = m.groupBy(i => i % 2)
val t = for ((i, o) <- g; n <- o) yield n
assertEquals(List(1, 2, 3, 4), t.toBlocking.toList)
}
@Test def testGroupByThenFlatMapByForComprehensionWithTiming(): Unit = {
val m = Observable.interval(100 millis).take(4)
val g = m.groupBy(i => i % 2)
val t = for ((i, o) <- g; n <- o) yield n
assertEquals(List(0, 1, 2, 3), t.toBlocking.toList)
}
@Test def timingTest(): Unit = {
val firstOnly = false
val numbersByModulo3 = Observable.interval(1000 millis).take(9).groupBy(_ % 3)
(for ((modulo, numbers) <- numbersByModulo3) yield {
println("Observable for modulo" + modulo + " started")
if (firstOnly) numbers.take(1) else numbers
}).flatten.toBlocking.foreach(println(_))
}
@Test def timingTest1(): Unit = {
val numbersByModulo3 = Observable.interval(1000 millis).take(9).groupBy(_ % 3)
val t0 = System.currentTimeMillis
(for ((modulo, numbers) <- numbersByModulo3) yield {
println("Observable for modulo" + modulo + " started at t = " + (System.currentTimeMillis - t0))
numbers.map(n => s"${n} is in the modulo-$modulo group")
}).flatten.toBlocking.foreach(println(_))
}
@Test def testOlympicYearTicks(): Unit = {
Olympics.yearTicks.subscribe(println(_))
waitFor(Olympics.yearTicks)
}
@Test def groupByExample(): Unit = {
val medalsByCountry = Olympics.mountainBikeMedals.groupBy(medal => medal.country)
val firstMedalOfEachCountry =
for ((country, medals) <- medalsByCountry; firstMedal <- medals.take(1)) yield firstMedal
firstMedalOfEachCountry.subscribe(medal => {
println(s"${medal.country} wins its first medal in ${medal.year}")
})
Olympics.yearTicks.subscribe(year => println(s"\nYear $year starts."))
waitFor(Olympics.yearTicks)
}
@Test def groupByExample2(): Unit = {
val medalByYear = Olympics.mountainBikeMedals.groupBy(medal => medal.year, medal => medal.country)
for ((year, countries) <- medalByYear; country <- countries) {
println(s"${year}: ${country}")
}
Olympics.yearTicks.subscribe(year => println(s"\nYear $year starts."))
waitFor(Olympics.yearTicks)
}
@Test def combineLatestExample(): Unit = {
val firstCounter = Observable.interval(250 millis)
val secondCounter = Observable.interval(550 millis)
val combinedCounter = firstCounter.combineLatestWith(secondCounter)(List(_, _)) take 10
combinedCounter subscribe {x => println(s"Emitted group: $x")}
waitFor(combinedCounter)
}
@Test def combineLatestExample2(): Unit = {
val firstCounter = Observable.interval(250 millis)
val secondCounter = Observable.interval(550 millis)
val thirdCounter = Observable.interval(850 millis)
val sources = Iterable(firstCounter, secondCounter, thirdCounter)
val combinedCounter = Observable.combineLatest(sources)(_.toList).take(10)
combinedCounter subscribe {x => println(s"Emitted group: $x")}
waitFor(combinedCounter)
}
@Test def combineLatestDelayErrorExample(): Unit = {
val firstCounter = Observable.just(1) ++ Observable.error(new RuntimeException("Oops!"))
val secondCounter = Observable.interval(550 millis).take(3)
val sources = Iterable(firstCounter, secondCounter)
Observable.combineLatest(sources)(_.toList).subscribe(
i => println("combineLatest: " + i),
e => println("combineLatest: " + e.getMessage))
Thread.sleep(2000)
Observable.combineLatestDelayError(sources)(_.toList).subscribe(
i => println("combineLatestDelayError: " + i),
e => println("combineLatestDelayError: " + e.getMessage))
Thread.sleep(2000)
}
@Test def olympicsExampleWithoutPublish(): Unit = {
val medals = Olympics.mountainBikeMedals.doOnEach(_ => println("onNext"))
medals.subscribe(println(_)) // triggers an execution of medals Observable
waitFor(medals) // triggers another execution of medals Observable
}
@Test def olympicsExampleWithPublish(): Unit = {
val medals = Olympics.mountainBikeMedals.doOnEach(_ => println("onNext")).publish
medals.subscribe(println(_)) // triggers an execution of medals Observable
medals.connect
waitFor(medals) // triggers another execution of medals Observable
}
@Test def exampleWithoutPublish(): Unit = {
val unshared = Observable.from(1 to 4)
unshared.subscribe(n => println(s"subscriber 1 gets $n"))
unshared.subscribe(n => println(s"subscriber 2 gets $n"))
}
@Test def exampleWithPublish(): Unit = {
val unshared = Observable.from(1 to 4)
val shared = unshared.publish
shared.subscribe(n => println(s"subscriber 1 gets $n"))
shared.subscribe(n => println(s"subscriber 2 gets $n"))
shared.connect
}
@Test def exampleWithPublish2(): Unit = {
val o = Observable.interval(100 millis).take(5).publish((o: Observable[Long]) => o.map(_ * 2))
o.subscribe(n => println(s"subscriber 1 gets $n"))
o.subscribe(n => println(s"subscriber 2 gets $n"))
Thread.sleep(1000)
}
def doLater(waitTime: Duration, action: () => Unit): Unit = {
Observable.interval(waitTime).take(1).subscribe(_ => action())
}
@Test def exampleWithoutReplay(): Unit = {
val numbers = Observable.interval(1000 millis).take(6)
val sharedNumbers = numbers.publish
sharedNumbers.subscribe(n => println(s"subscriber 1 gets $n"))
sharedNumbers.connect
// subscriber 2 misses 0, 1, 2!
doLater(3500 millis, () => { sharedNumbers.subscribe(n => println(s"subscriber 2 gets $n")) })
waitFor(sharedNumbers)
}
@Test def exampleWithReplay(): Unit = {
val numbers = Observable.interval(1000 millis).take(6)
val sharedNumbers = numbers.replay
sharedNumbers.subscribe(n => println(s"subscriber 1 gets $n"))
sharedNumbers.connect
// subscriber 2 subscribes later but still gets all numbers
doLater(3500 millis, () => { sharedNumbers.subscribe(n => println(s"subscriber 2 gets $n")) })
waitFor(sharedNumbers)
}
@Test def exampleWithReplay2(): Unit = {
val numbers = Observable.interval(100 millis).take(10)
val sharedNumbers = numbers.replay(3)
sharedNumbers.subscribe(n => println(s"subscriber 1 gets $n"))
sharedNumbers.connect
// subscriber 2 subscribes later but only gets the 3 buffered numbers and the following numbers
Thread.sleep(700)
sharedNumbers.subscribe(n => println(s"subscriber 2 gets $n"))
waitFor(sharedNumbers)
}
@Test def exampleWithReplay3(): Unit = {
val numbers = Observable.interval(100 millis).take(10)
val sharedNumbers = numbers.replay(300 millis)
sharedNumbers.subscribe(n => println(s"subscriber 1 gets $n"))
sharedNumbers.connect
// subscriber 2 subscribes later but only gets the buffered numbers and the following numbers
Thread.sleep(700)
sharedNumbers.subscribe(n => println(s"subscriber 2 gets $n"))
waitFor(sharedNumbers)
}
@Test def exampleWithReplay4(): Unit = {
val numbers = Observable.interval(100 millis).take(10)
val sharedNumbers = numbers.replay(2, 300 millis)
sharedNumbers.subscribe(n => println(s"subscriber 1 gets $n"))
sharedNumbers.connect
// subscriber 2 subscribes later but only gets the buffered numbers and the following numbers
Thread.sleep(700)
sharedNumbers.subscribe(n => println(s"subscriber 2 gets $n"))
waitFor(sharedNumbers)
}
@Test def exampleWithReplay5(): Unit = {
val numbers = Observable.interval(100 millis).take(10)
val sharedNumbers = numbers.replay(o => o.map(_ * 2))
sharedNumbers.subscribe(n => println(s"subscriber gets $n"))
waitFor(sharedNumbers)
}
@Test def testSingleOption(): Unit = {
assertEquals(Some(1), List(1).toObservable.toBlocking.singleOption)
assertEquals(None, List().toObservable.toBlocking.singleOption)
}
// We can't put a general average method into Observable.scala, because Scala's Numeric
// does not have scalar multiplication (we would need to calculate (1.0/numberOfElements)*sum)
def doubleAverage(o: Observable[Double]): Observable[Double] = {
for ((finalSum, finalCount) <- o.foldLeft((0.0, 0))({case ((sum, count), elem) => (sum+elem, count+1)}))
yield finalSum / finalCount
}
@Test def averageExample(): Unit = {
println(doubleAverage(Observable.empty).toBlocking.single)
println(doubleAverage(List(0.0).toObservable).toBlocking.single)
println(doubleAverage(List(4.44).toObservable).toBlocking.single)
println(doubleAverage(List(1.0, 2.0, 3.5).toObservable).toBlocking.single)
}
@Test def testSum(): Unit = {
assertEquals(10, List(1, 2, 3, 4).toObservable.sum.toBlocking.single)
assertEquals(6, List(4, 2).toObservable.sum.toBlocking.single)
assertEquals(0, List[Int]().toObservable.sum.toBlocking.single)
}
@Test def testProduct(): Unit = {
assertEquals(24, List(1, 2, 3, 4).toObservable.product.toBlocking.single)
assertEquals(8, List(4, 2).toObservable.product.toBlocking.single)
assertEquals(1, List[Int]().toObservable.product.toBlocking.single)
}
@Test def mapWithIndexExample(): Unit = {
// We don't need mapWithIndex because we already have zipWithIndex, which we can easily
// combine with map:
List("a", "b", "c").toObservable.zipWithIndex.map(pair => pair._1 + " has index " + pair._2)
.toBlocking.foreach(println(_))
// Or even nicer with for-comprehension syntax:
(for ((letter, index) <- List("a", "b", "c").toObservable.zipWithIndex) yield letter + " has index " + index)
.toBlocking.foreach(println(_))
}
// source Observables are all known:
@Test def zip3Example(): Unit = {
val o = Observable.zip(List(1, 2).toObservable, List(10, 20).toObservable, List(100, 200).toObservable)
(for ((n1, n2, n3) <- o) yield s"$n1, $n2 and $n3")
.toBlocking.foreach(println(_))
}
// source Observables are in an Observable:
@Test def zipManyObservableExample(): Unit = {
val observables = List(List(1, 2).toObservable, List(10, 20).toObservable, List(100, 200).toObservable).toObservable
(for (seq <- Observable.zip(observables)) yield seq.mkString("(", ", ", ")"))
.toBlocking.foreach(println(_))
}
/**
* This is a bad way of using `zip` with an `Iterable`: even if the consumer unsubscribes,
* some elements may still be pulled from `Iterable`.
*/
@Test def zipWithIterableBadExample(): Unit = {
val o1 = Observable.interval(100 millis, IOScheduler()).map(_ * 100).take(3)
val o2 = Observable.from(0 until Int.MaxValue).doOnEach(i => println(i + " from o2"))
o1.zip(o2).toBlocking.foreach(println(_))
}
/**
* This is a good way of using `zip` with an `Iterable`: if the consumer unsubscribes,
* no more elements will be pulled from `Iterable`.
*/
@Test def zipWithIterableGoodExample(): Unit = {
val o1 = Observable.interval(100 millis, IOScheduler()).map(_ * 100).take(3)
val iter = (0 until Int.MaxValue).view.map {
i => {
println(i + " from iter")
i
}
}
o1.zip(iter).toBlocking.foreach(println(_))
}
@Test def zipWithExample(): Unit = {
val xs = Observable.just(1, 3, 5, 7)
val ys = Observable.just(2, 4, 6, 8)
xs.zipWith(ys)(_ * _).subscribe(println(_))
}
@Test def takeFirstWithCondition(): Unit = {
val condition: Int => Boolean = _ >= 3
assertEquals(3, List(1, 2, 3, 4).toObservable.filter(condition).first.toBlocking.single)
}
@Test def firstOrDefaultWithCondition(): Unit = {
val condition: Int => Boolean = _ >= 3
assertEquals(3, List(1, 2, 3, 4).toObservable.filter(condition).firstOrElse(10).toBlocking.single)
assertEquals(10, List(-1, 0, 1).toObservable.filter(condition).firstOrElse(10).toBlocking.single)
}
@Test def firstLastSingleExample(): Unit = {
assertEquals(1, List(1, 2, 3, 4).toObservable.head.toBlocking.single)
assertEquals(1, List(1, 2, 3, 4).toObservable.first.toBlocking.single)
assertEquals(4, List(1, 2, 3, 4).toObservable.last.toBlocking.single)
assertEquals(1, List(1).toObservable.single.toBlocking.single)
assertEquals(1, List(1, 2, 3, 4).toObservable.toBlocking.head)
assertEquals(1, List(1, 2, 3, 4).toObservable.toBlocking.first)
assertEquals(4, List(1, 2, 3, 4).toObservable.toBlocking.last)
assertEquals(1, List(1).toObservable.toBlocking.single)
}
@Test def dropExample(): Unit = {
val o = List(1, 2, 3, 4).toObservable
assertEquals(List(3, 4), o.drop(2).toBlocking.toList)
}
@Test def dropWithTimeExample(): Unit = {
val o = List(1, 2, 3, 4).toObservable.zip(
Observable.interval(500 millis, IOScheduler())).map(_._1) // emit every 500 millis
println(
o.drop(1250 millis, IOScheduler()).toBlocking.toList // output List(3, 4)
)
}
@Test def dropRightExample(): Unit = {
val o = List(1, 2, 3, 4).toObservable
assertEquals(List(1, 2), o.dropRight(2).toBlocking.toList)
}
@Test def dropRightWithTimeExample(): Unit = {
val o = List(1, 2, 3, 4).toObservable.zip(
Observable.interval(500 millis, IOScheduler())).map(_._1) // emit every 500 millis
println(
o.dropRight(750 millis, IOScheduler()).toBlocking.toList // output List(1, 2)
)
}
@Test def dropUntilExample(): Unit = {
val o = List("Alice", "Bob", "Carlos").toObservable.zip(
Observable.interval(700 millis, IOScheduler())).map(_._1) // emit every 700 millis
val other = List(1).toObservable.delay(1 seconds)
println(
o.dropUntil(other).toBlocking.toList // output List("Bob", "Carlos")
)
}
def square(x: Int): Int = {
println(s"$x*$x is being calculated on thread ${Thread.currentThread().getId}")
Thread.sleep(100) // calculating a square is heavy work :)
x*x
}
@Test def toSortedList(): Unit = {
assertEquals(Seq(7, 8, 9, 10), List(10, 7, 8, 9).toObservable.toSeq.map(_.sorted).toBlocking.single)
val f = (a: Int, b: Int) => b < a
assertEquals(Seq(10, 9, 8, 7), List(10, 7, 8, 9).toObservable.toSeq.map(_.sortWith(f)).toBlocking.single)
}
@Test def timestampExample(): Unit = {
val timestamped = Observable.interval(100 millis).take(6).timestamp.toBlocking
for ((millis, value) <- timestamped if value > 0) {
println(value + " at t = " + millis)
}
}
@Test def materializeExample1(): Unit = {
def printObservable[T](o: Observable[T]): Unit = {
import Notification._
o.materialize.subscribe(n => n match {
case OnNext(v) => println("Got value " + v)
case OnCompleted => println("Completed")
case OnError(err) => println("Error: " + err.getMessage)
})
}
val o1 = Observable.interval(100 millis).take(3)
val o2 = Observable.error(new IOException("Oops"))
printObservable(o1)
printObservable(o2)
Thread.sleep(500)
}
@Test def materializeExample2(): Unit = {
import Notification._
List(1, 2, 3).toObservable.materialize.subscribe(n => n match {
case OnNext(v) => println("Got value " + v)
case OnCompleted => println("Completed")
case OnError(err) => println("Error: " + err.getMessage)
})
}
@Test def notificationSubtyping(): Unit = {
import Notification._
val oc1: Notification[Nothing] = OnCompleted
val oc2: Notification[Int] = OnCompleted
val oc3: rx.Notification[_ <: Int] = JavaConversions.toJavaNotification(oc2)
val oc4: rx.Notification[_ <: Any] = JavaConversions.toJavaNotification(oc2)
}
@Test def takeWhileWithIndexAlternative: Unit = {
val condition = true
List("a", "b").toObservable.zipWithIndex.takeWhile{case (elem, index) => condition}.map(_._1)
}
def calculateElement(index: Int): String = {
println("omg I'm calculating so hard")
index match {
case 0 => "a"
case 1 => "b"
case _ => throw new IllegalArgumentException
}
}
/**
* Using AsyncOnSubscribe of SyncOnSubscribe ensures that your Observable
* does not calculate elements after the consumer unsubscribes and correctly does not overload
* the subscriber with data (responds to backpressure).
*
* Here we create a SyncOnSubscribe without state, this means that it performs the same action every time downstream can handle more data.
*/
@Test def createExample(): Unit = {
val o = Observable.create(SyncOnSubscribe.stateless(
next = () => Notification.OnNext(math.random),
onUnsubscribe = () => println("I have stopped generating random numbers for this subscriber")
))
o.take(10).foreach(r => println(s"Next random number: $r"))
}
/**
* You can also add state to (A)SyncOnSubscribe, you generate a state on each subscription and can alter that state in each next call
* Here we use it to count to a specific number
*/
@Test def createExampleWithState(): Unit = {
// Starts with state `0`
val o = Observable.create(SyncOnSubscribe(() => 0)(i => {
if(i < 2)
// Check if the state has reached 2 yet, if not, we emit the current state and add 1 to the state
(Notification.OnNext(i), i+1)
else
// Otherwise we signal completion
(Notification.OnCompleted, i)
}))
o.take(1).subscribe(println(_))
}
/**
* This example shows how to read a (potentially blocking) data source step-by-step (line by line) using SyncOnSubscribe.
*/
@Test def createExampleFromInputStream(): Unit = {
import scala.io.{Codec, Source}
val rxscalaURL = "http://reactivex.io/rxscala/"
// We use the `singleState` helper here, since we only want to generate one state per subscriber
// and do not need to modify it afterwards
val rxscala = Observable.create(SyncOnSubscribe.singleState(
// This is our `generator`, which generates a state
generator = () => {
val input = new java.net.URL(rxscalaURL).openStream()
(input, Source.fromInputStream(input)(Codec.UTF8).getLines())
})(
// This is our `next` function, which gets called whenever the subscriber can handle more data
next = {
case (_, lines) => {
if(lines.hasNext)
// Here we provide the next line
Notification.OnNext(lines.next())
else
// Here we signal that the stream has completed
Notification.OnCompleted
}
},
// This is our `onUnsubscribe` function, which gets called after the subscriber unsubscribes, usually to perform cleanup
onUnsubscribe = {
case (input, _) => scala.util.Try { input.close() }
}
)).subscribeOn(IOScheduler())
val count = rxscala.flatMap(_.split("\\W+").toSeq.toObservable)
.map(_.toLowerCase)
.filter(_ == "rxscala")
.size
println(s"RxScala appears ${count.toBlocking.single} times in ${rxscalaURL}")
}
/** This example show how to generate an Observable using AsyncOnSubscribe, which can be more efficient than SyncOnSubscribe.
* Using AsyncOnSubscribe has the same advantages as SyncOnSubscribe, and furthermore it allows us to generate more than one
* result at a time (which can be more efficient) and allows us to generate the results asynchronously.
*/
@Test def createExampleAsyncOnUnsubscribe(): Unit = {
// We are going to count to this number
val countTo = 200L
val o = Observable.create(AsyncOnSubscribe(() => 0L)(
(count, demand) => {
// Stop counting if we're past the number we were going to count to
if(count > countTo)
(Notification.OnCompleted, count)
else {
// Generate an observable that contains [count,count+demand) and thus contains exactly `demand` items
val to = math.min(count + demand, countTo+1)
val range = count until to
val resultObservable = Observable.from(range)
println(s"Currently at $count, received a demand of $demand. Next range [$count,$to)")
(Notification.OnNext(resultObservable), to)
}
}
))
o.subscribe(new Subscriber[Long] {
override def onStart(): Unit = request(10)
override def onNext(i: Long): Unit = {
request(scala.util.Random.nextInt(10)+1)
}
})
}
def output(s: String): Unit = println(s)
/** Subscribes to obs and waits until obs has completed. Note that if you subscribe to
* obs yourself and also call waitFor(obs), all side-effects of subscribing to obs
* will happen twice.
*/
def waitFor[T](obs: Observable[T]): Unit = {
obs.toBlocking.toIterable.last
}
@Test def doOnCompletedExample(): Unit = {
val o = List("red", "green", "blue").toObservable.doOnCompleted { println("onCompleted") }
o.subscribe(v => println(v), e => e.printStackTrace)
// red
// green
// blue
// onCompleted
}
@Test def doOnSubscribeExample(): Unit = {
val o = List("red", "green", "blue").toObservable.doOnSubscribe { println("subscribed") }
o.subscribe(v => println(v), e => e.printStackTrace, () => println("onCompleted"))
// subscribed
// red
// green
// blue
// onCompleted
}
@Test def doOnTerminateExample(): Unit = {
val o = List("red", "green", "blue").toObservable.doOnTerminate { println("terminate") }
o.subscribe(v => println(v), e => e.printStackTrace, () => println("onCompleted"))
// red
// green
// blue
// terminate
// onCompleted
}
@Test def doOnUnsubscribeExample(): Unit = {
val o = List("red", "green", "blue").toObservable.doOnUnsubscribe { println("unsubscribed") }
o.subscribe(v => println(v), e => e.printStackTrace, () => println("onCompleted"))
// red
// green
// blue
// onCompleted
// unsubscribed
}
@Test def doAfterTerminateExample(): Unit = {
val o = List("red", "green", "blue").toObservable.doAfterTerminate { println("finally") }
o.subscribe(v => println(v), e => e.printStackTrace, () => println("onCompleted"))
// red
// green
// blue
// onCompleted
// finally
}
@Test def timeoutExample(): Unit = {
val other = List(100L, 200L, 300L).toObservable
val result = Observable.interval(100 millis).timeout(50 millis, other).toBlocking.toList
println(result)
}
@Test def timeoutExample2(): Unit = {
val firstTimeoutSelector = () => {
Observable.interval(10 seconds, 10 seconds, ComputationScheduler()).take(1)
}
val timeoutSelector = (t: Long) => {
Observable.interval(
(500 - t * 100) max 1 millis,
(500 - t * 100) max 1 millis,
ComputationScheduler()).take(1)
}
val other = List(100L, 200L, 300L).toObservable
val result = Observable.interval(100 millis).timeout(firstTimeoutSelector, timeoutSelector, other).toBlocking.toList
println(result)
}
@Test def ambExample(): Unit = {
val o1 = List(100L, 200L, 300L).toObservable.delay(4 seconds)
val o2 = List(1000L, 2000L, 3000L).toObservable.delay(2 seconds)
val result = o1.amb(o2).toBlocking.toList
println(result)
}
@Test def ambWithVarargsExample(): Unit = {
val o1 = List(100L, 200L, 300L).toObservable.delay(4 seconds)
val o2 = List(1000L, 2000L, 3000L).toObservable.delay(2 seconds)
val o3 = List(10000L, 20000L, 30000L).toObservable.delay(4 seconds)
val result = Observable.amb(o1, o2, o3).toBlocking.toList
println(result)
}
@Test def ambWithSeqExample(): Unit = {
val o1 = List(100L, 200L, 300L).toObservable.delay(4 seconds)
val o2 = List(1000L, 2000L, 3000L).toObservable.delay(2 seconds)
val o3 = List(10000L, 20000L, 30000L).toObservable.delay(4 seconds)
val o = Seq(o1, o2, o3)
val result = Observable.amb(o: _*).toBlocking.toList
println(result)
}
@Test def delayExample(): Unit = {
val o = List(100L, 200L, 300L).toObservable.delay(2 seconds)
val result = o.toBlocking.toList
println(result)
}
@Test def delayExample2(): Unit = {
val o = List(100L, 200L, 300L).toObservable.delay(2 seconds, IOScheduler())
val result = o.toBlocking.toList
println(result)
}
@Test def delayExample3(): Unit = {
val o = List(100, 500, 200).toObservable.delay(
(i: Int) => Observable.just(i).delay(i millis)
)
o.toBlocking.foreach(println(_))
}
@Test def delayExample4(): Unit = {
val o = List(100, 500, 200).toObservable.delay(
() => Observable.interval(500 millis).take(1),
(i: Int) => Observable.just(i).delay(i millis)
)
o.toBlocking.foreach(println(_))
}
@Test def delaySubscriptionExample(): Unit = {
val o = List(100L, 200L, 300L).toObservable.delaySubscription(2 seconds)
val result = o.toBlocking.toList
println(result)
}
@Test def delaySubscriptionExample2(): Unit = {
val o = List(100L, 200L, 300L).toObservable.delaySubscription(2 seconds, IOScheduler())
val result = o.toBlocking.toList
println(result)
}
@Test def elementAtExample(): Unit = {
val o = List("red", "green", "blue").toObservable
println(o.elementAt(2).toBlocking.single)
}
@Test def elementAtOrDefaultExample(): Unit = {
val o : Observable[Seq[Char]] = List("red".toList, "green".toList, "blue".toList).toObservable.elementAtOrDefault(3, "black".toSeq)
println(o.toBlocking.single)
}
@Test def toMapExample1(): Unit = {
val o : Observable[String] = List("alice", "bob", "carol").toObservable
val keySelector = (s: String) => s.head