├── Part 1 - Getting Started ├── 1. Why Rx.md ├── 2. Key types.md └── 3. Lifetime management.md ├── Part 2 - Sequence Basics ├── 1. Creating a sequence.md ├── 2. Reducing a sequence.md ├── 3. Inspection.md ├── 4. Aggregation.md └── 5. Transformation of sequences.md ├── Part 3 - Taming the sequence ├── 1. Side effects.md ├── 2. Leaving the monad.md ├── 3. Advanced error handling.md ├── 4. Combining sequences.md ├── 5. Time-shifted sequences.md ├── 6. Hot and Cold observables.md └── 7. Custom operators.md ├── Part 4 - Concurrency ├── 1. Scheduling and threading.md ├── 2. Testing Rx.md ├── 3. Sequences of coincidence.md └── 4. Backpressure.md ├── README.md └── tests └── java └── itrx ├── chapter1 ├── AsyncSubjectExample.java ├── BehaviorSubjectExample.java ├── PublishSubjectExample.java ├── ReplaySubjectExample.java ├── RxContractExample.java └── UnsubscribingExample.java ├── chapter2 ├── aggregation │ ├── CollectExample.java │ ├── CountExample.java │ ├── FirstExample.java │ ├── GroupByExample.java │ ├── LastExample.java │ ├── NestExample.java │ ├── ReduceExample.java │ ├── ScanExample.java │ ├── SingleExample.java │ ├── ToCollectionExample.java │ └── ToMapExample.java ├── creating │ ├── FromExample.java │ ├── FunctionalUnfoldsExample.java │ └── ObservableFactoriesExample.java ├── inspection │ ├── AllExample.java │ ├── ContainsExample.java │ ├── DefaultIfEmptyExample.java │ ├── ElementAtExample.java │ ├── ExistsExample.java │ ├── IsEmptyExample.java │ └── SequenceEqualExample.java ├── reducing │ ├── DistinctExample.java │ ├── FilterExample.java │ ├── IgnoreExample.java │ └── TakeSkipExample.java └── transforming │ ├── CastTypeOfExample.java │ ├── ConcatMapExample.java │ ├── FlatMapExample.java │ ├── FlatMapIterableExample.java │ ├── MapExample.java │ ├── MaterializeExample.java │ └── TimestampTimeIntervalExample.java ├── chapter3 ├── combining │ ├── AmbExample.java │ ├── CombineLatestExample.java │ ├── ConcatExample.java │ ├── MergeDelayErrorExample.java │ ├── MergeExample.java │ ├── RepeatExample.java │ ├── StartWithExample.java │ ├── SwitchMapExample.java │ ├── SwitchOnNextExample.java │ └── ZipExample.java ├── custom │ ├── ComposeExample.java │ ├── LiftExample.java │ └── SerializeExample.java ├── error │ ├── ResumeExample.java │ ├── RetryExample.java │ ├── RetryWhenExample.java │ └── UsingExample.java ├── hotandcold │ ├── CacheExample.java │ ├── ColdExample.java │ ├── ConnectableObservableExample.java │ ├── MulticastExample.java │ └── ReplayExample.java ├── leaving │ ├── FirstLastSingleExample.java │ ├── ForEachExample.java │ ├── FutureExample.java │ └── IterablesExample.java ├── sideeffects │ ├── AsObservableExample.java │ ├── DoOnExample.java │ ├── MutablePipelineExample.java │ └── SideEffectExample.java └── timeshifted │ ├── BufferExample.java │ ├── DebounceExample.java │ ├── DelayExample.java │ ├── SampleExample.java │ ├── TakeLastBufferExample.java │ ├── ThrottleExample.java │ └── TimeoutExample.java └── chapter4 ├── backpressure ├── ConsumerSideExample.java ├── ControlledPullSubscriber.java ├── NoBackpressureExample.java ├── OnBackpressureExample.java ├── OnRequestExample.java └── ReactivePullExample.java ├── coincidence ├── GroupJoinExample.java ├── JoinExample.java └── WindowExample.java ├── scheduling ├── ObserveOnExample.java ├── SchedulerExample.java ├── SchedulersExample.java ├── SingleThreadedExample.java ├── SubscribeOnExample.java └── UnsubscribeOnExample.java └── testing ├── ExampleExample.java ├── TestSchedulerExample.java └── TestSubscriberExample.java /Part 1 - Getting Started/1. Why Rx.md: -------------------------------------------------------------------------------- 1 | # PART 1 - Getting started 2 | 3 | ## Why Rx 4 | 5 | > Users expect real time data. They want their tweets now. Their order confirmed now. They need prices accurate as of now. Their online games need to be responsive. As a developer, you demand fire-and-forget messaging. You don't want to be blocked waiting for a result. You want to have the result pushed to you when it is ready. Even better, when working with result sets, you want to receive individual results as they are ready. You do not want to wait for the entire set to be processed before you see the first row. The world has moved to push; users are waiting for us to catch up. Developers have tools to push data, this is easy. Developers need tools to react to push data 6 | 7 | Welcome to Rx. This book is based on [Rx.NET](http://msdn.microsoft.com/en-us/devlabs/gg577609)'s www.introtorx.com and it introduces beginners to [RxJava](https://github.com/ReactiveX/RxJava), the Netflix implementation of the original Microsoft library. Rx is a powerful tool that enables the solution of problems in an elegant declarative style, familiar to functional programmers. Rx has several benefits: 8 | 9 | * Unitive 10 | * Queries in Rx are done in the same style as other libraries inspired by functional programming, such as Java streams. In Rx, one can use functional style transformations on event streams. 11 | * Extensible 12 | * RxJava can be extended with custom operators. Although Java does not allow for this to happen in an elegant way, RxJava offers all the extensibility one can find Rx implementations in other languages. 13 | * Declarative 14 | * Functional transformations are read in a declarative way. 15 | * Composable 16 | * Rx operators can be combined to produce more complicated operations. 17 | * Transformative 18 | * Rx operators can transform one type of data to another, reducing, mapping or expanding streams as needed. 19 | 20 | 21 | ## When is Rx appropriate? 22 | 23 | Rx is fit for composing and consuming sequences of events. We present some of the use cases for Rx, according to www.introtorx.com 24 | 25 | ### Should use Rx 26 | 27 | * UI events like mouse move, button click 28 | * Domain events like property changed, collection updated, "Order Filled", "Registration accepted" etc. 29 | * Infrastructure events like from file watcher, system and WMI events 30 | * Integration events like a broadcast from a message bus or a push event from WebSockets API or other low latency middleware like Nirvana 31 | * Integration with a CEP engine like StreamInsight or StreamBase. 32 | 33 | ### Could use Rx 34 | 35 | * Result of `Future` or equivalent pattern 36 | 37 | Those patterns are already well adopted and you may find that introducing Rx on top of that does not add to the development process. 38 | 39 | ### Won't use Rx 40 | 41 | * Translating iterables to observables, just for the sake of working on them through an Rx library. 42 | 43 | 44 | ##### Continue reading 45 | 46 | | Previous | Next | 47 | | --- | --- | 48 | | | [Key types](/Part 1 - Getting Started/2. Key types.md) | 49 | 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Intro to RxJava 2 | 3 | This guide aims to introduce a beginner reactive programmer to the complete power of the [RxJava](https://github.com/ReactiveX/RxJava) implementation of reactive programming for the JVM. It is based on the [IntroToRx](http://www.introtorx.com) guide for Rx.NET. 4 | 5 | No experience with either reactive or functional programming is needed to follow the book. Familiarity with the basics of Java is required. 6 | 7 | [Begin learning](/Part 1 - Getting Started/1. Why Rx.md) 8 | 9 | ### Structure 10 | 11 | The content of this book is meant to be read from start to finish. It is bigger than your average tutorial and smaller than an actual book. It begins with the basics and every subsequent chapter introduces increasingly advanced features and concepts. Sections of the book are intended to be self-containing and to-the-point, so that the book can be referred back to by non-beginners. 12 | 13 | The examples used in the book are also [available in compilable java files](/tests/java/itrx) in two formats: 14 | * Examples that print to standard output (recommended for first-time readers) 15 | * Silent, self-checking examples in the form of [JUnit](http://junit.org/) tests. 16 | The readers are invited to study whichever style suits them best. 17 | 18 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/AsyncSubjectExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.observers.TestSubscriber; 32 | import rx.subjects.AsyncSubject; 33 | 34 | public class AsyncSubjectExample { 35 | 36 | public void exampleLastValue() { 37 | AsyncSubject s = AsyncSubject.create(); 38 | s.subscribe(v -> System.out.println(v)); 39 | s.onNext(0); 40 | s.onNext(1); 41 | s.onNext(2); 42 | s.onCompleted(); 43 | 44 | // 2 45 | } 46 | 47 | public void exampleNoCompletion() { 48 | AsyncSubject s = AsyncSubject.create(); 49 | s.subscribe(v -> System.out.println(v)); 50 | s.onNext(0); 51 | s.onNext(1); 52 | s.onNext(2); 53 | } 54 | 55 | // 56 | // Tests 57 | // 58 | 59 | @Test 60 | public void testLastValue() { 61 | TestSubscriber tester = new TestSubscriber(); 62 | 63 | AsyncSubject s = AsyncSubject.create(); 64 | s.subscribe(tester); 65 | s.onNext(0); 66 | s.onNext(1); 67 | s.onNext(2); 68 | s.onCompleted(); 69 | 70 | tester.assertReceivedOnNext(Arrays.asList(2)); 71 | tester.assertTerminalEvent(); 72 | tester.assertNoErrors(); 73 | } 74 | 75 | @Test 76 | public void testNoCompletion() { 77 | TestSubscriber tester = new TestSubscriber(); 78 | 79 | AsyncSubject s = AsyncSubject.create(); 80 | s.subscribe(tester); 81 | s.onNext(0); 82 | s.onNext(1); 83 | s.onNext(2); 84 | 85 | tester.assertReceivedOnNext(Arrays.asList()); 86 | assertTrue(tester.getOnCompletedEvents().size() == 0); 87 | tester.assertNoErrors(); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/BehaviorSubjectExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.observers.TestSubscriber; 30 | import rx.subjects.BehaviorSubject; 31 | 32 | public class BehaviorSubjectExample { 33 | 34 | public void exampleLate() { 35 | BehaviorSubject s = BehaviorSubject.create(); 36 | s.onNext(0); 37 | s.onNext(1); 38 | s.onNext(2); 39 | s.subscribe(v -> System.out.println("Late: " + v)); 40 | s.onNext(3); 41 | 42 | // Late: 2 43 | // Late: 3 44 | } 45 | 46 | public void exampleCompleted() { 47 | BehaviorSubject s = BehaviorSubject.create(); 48 | s.onNext(0); 49 | s.onNext(1); 50 | s.onNext(2); 51 | s.onCompleted(); 52 | s.subscribe( 53 | v -> System.out.println("Late: " + v), 54 | e -> System.out.println("Error"), 55 | () -> System.out.println("Completed") 56 | ); 57 | } 58 | 59 | public void exampleInitialvalue() { 60 | BehaviorSubject s = BehaviorSubject.create(0); 61 | s.subscribe(v -> System.out.println(v)); 62 | s.onNext(1); 63 | 64 | // 0 65 | // 1 66 | } 67 | 68 | 69 | // 70 | // Tests 71 | // 72 | 73 | @Test 74 | public void testLate() { 75 | TestSubscriber tester = new TestSubscriber(); 76 | 77 | BehaviorSubject s = BehaviorSubject.create(); 78 | s.onNext(0); 79 | s.onNext(1); 80 | s.onNext(2); 81 | s.subscribe(tester); 82 | s.onNext(3); 83 | 84 | tester.assertReceivedOnNext(Arrays.asList(2,3)); 85 | } 86 | 87 | @Test 88 | public void testCompleted() { 89 | TestSubscriber tester = new TestSubscriber(); 90 | 91 | BehaviorSubject s = BehaviorSubject.create(); 92 | s.onNext(0); 93 | s.onNext(1); 94 | s.onNext(2); 95 | s.onCompleted(); 96 | s.subscribe(tester); 97 | 98 | tester.assertReceivedOnNext(Arrays.asList()); 99 | tester.assertTerminalEvent(); 100 | tester.assertNoErrors(); 101 | } 102 | 103 | @Test 104 | public void testInitialvalue() { 105 | TestSubscriber tester = new TestSubscriber(); 106 | 107 | BehaviorSubject s = BehaviorSubject.create(0); 108 | s.subscribe(tester); 109 | s.onNext(1); 110 | 111 | tester.assertReceivedOnNext(Arrays.asList(0,1)); 112 | tester.assertNoErrors(); 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/PublishSubjectExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.observers.TestSubscriber; 30 | import rx.subjects.PublishSubject; 31 | 32 | public class PublishSubjectExample { 33 | 34 | public void example() { 35 | PublishSubject subject = PublishSubject.create(); 36 | subject.onNext(1); 37 | subject.subscribe(System.out::println); 38 | subject.onNext(2); 39 | subject.onNext(3); 40 | subject.onNext(4); 41 | 42 | // 2 43 | // 3 44 | // 4 45 | } 46 | 47 | 48 | // 49 | // Test 50 | // 51 | 52 | @Test 53 | public void test() { 54 | TestSubscriber tester = new TestSubscriber<>(); 55 | 56 | PublishSubject subject = PublishSubject.create(); 57 | subject.onNext(1); 58 | subject.subscribe(tester); 59 | subject.onNext(2); 60 | subject.onNext(3); 61 | subject.onNext(4); 62 | 63 | tester.assertReceivedOnNext(Arrays.asList(2,3,4)); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/ReplaySubjectExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.observers.TestSubscriber; 31 | import rx.schedulers.Schedulers; 32 | import rx.schedulers.TestScheduler; 33 | import rx.subjects.ReplaySubject; 34 | 35 | public class ReplaySubjectExample { 36 | 37 | public void exampleEarlyLate() { 38 | ReplaySubject s = ReplaySubject.create(); 39 | s.subscribe(v -> System.out.println("Early:" + v)); 40 | s.onNext(0); 41 | s.onNext(1); 42 | s.subscribe(v -> System.out.println("Late: " + v)); 43 | s.onNext(2); 44 | 45 | // Early:0 46 | // Early:1 47 | // Late: 0 48 | // Late: 1 49 | // Early:2 50 | // Late: 2 51 | } 52 | 53 | public void exampleWithSize() { 54 | ReplaySubject s = ReplaySubject.createWithSize(2); 55 | s.onNext(0); 56 | s.onNext(1); 57 | s.onNext(2); 58 | s.subscribe(v -> System.out.println("Late: " + v)); 59 | s.onNext(3); 60 | 61 | // Late: 1 62 | // Late: 2 63 | // Late: 3 64 | } 65 | 66 | public void exampleWithTime() throws InterruptedException { 67 | ReplaySubject s = ReplaySubject.createWithTime(150, TimeUnit.MILLISECONDS, Schedulers.immediate()); 68 | s.onNext(0); 69 | Thread.sleep(100); 70 | s.onNext(1); 71 | Thread.sleep(100); 72 | s.onNext(2); 73 | s.subscribe(v -> System.out.println("Late: " + v)); 74 | s.onNext(3); 75 | 76 | // Late: 1 77 | // Late: 2 78 | // Late: 3 79 | } 80 | 81 | 82 | // 83 | // Test 84 | // 85 | 86 | @Test 87 | public void testEarlyLate() { 88 | TestSubscriber tester = new TestSubscriber(); 89 | 90 | ReplaySubject s = ReplaySubject.create(); 91 | s.subscribe(tester); 92 | s.onNext(0); 93 | s.onNext(1); 94 | s.subscribe(tester); 95 | s.onNext(2); 96 | 97 | tester.assertReceivedOnNext(Arrays.asList(0, 1, 0, 1, 2, 2)); 98 | } 99 | 100 | @Test 101 | public void testWithSize() { 102 | TestSubscriber tester = new TestSubscriber(); 103 | 104 | ReplaySubject s = ReplaySubject.createWithSize(2); 105 | s.onNext(0); 106 | s.onNext(1); 107 | s.onNext(2); 108 | s.subscribe(tester); 109 | s.onNext(3); 110 | 111 | tester.assertReceivedOnNext(Arrays.asList(1,2,3)); 112 | } 113 | 114 | @Test 115 | public void testWithTime() { 116 | TestSubscriber tester = new TestSubscriber(); 117 | TestScheduler scheduler = Schedulers.test(); 118 | 119 | ReplaySubject s = ReplaySubject.createWithTime(150, TimeUnit.MILLISECONDS, scheduler); 120 | s.onNext(0); 121 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 122 | s.onNext(1); 123 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 124 | s.onNext(2); 125 | s.subscribe(tester); 126 | s.onNext(3); 127 | 128 | tester.assertReceivedOnNext(Arrays.asList(1,2,3)); 129 | } 130 | 131 | 132 | } 133 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/RxContractExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.observers.TestSubscriber; 30 | import rx.subjects.ReplaySubject; 31 | import rx.subjects.Subject; 32 | 33 | public class RxContractExample { 34 | 35 | public void example() { 36 | Subject s = ReplaySubject.create(); 37 | s.subscribe(v -> System.out.println(v)); 38 | s.onNext(0); 39 | s.onCompleted(); 40 | s.onNext(1); 41 | s.onNext(2); 42 | 43 | // 0 44 | } 45 | 46 | public void examplePrintCompletion() { 47 | Subject values = ReplaySubject.create(); 48 | values.subscribe( 49 | v -> System.out.println(v), 50 | e -> System.out.println(e), 51 | () -> System.out.println("Completed") 52 | ); 53 | values.onNext(0); 54 | values.onNext(1); 55 | values.onCompleted(); 56 | values.onNext(2); 57 | 58 | // 0 59 | // 1 60 | } 61 | 62 | 63 | // 64 | // Test 65 | // 66 | 67 | @Test 68 | public void test() { 69 | TestSubscriber tester = new TestSubscriber(); 70 | 71 | Subject s = ReplaySubject.create(); 72 | s.subscribe(tester); 73 | s.onNext(0); 74 | s.onCompleted(); 75 | s.onNext(1); 76 | s.onNext(2); 77 | 78 | tester.assertReceivedOnNext(Arrays.asList(0)); 79 | tester.assertTerminalEvent(); 80 | tester.assertNoErrors(); 81 | } 82 | 83 | @Test 84 | public void testPrintCompletion() { 85 | TestSubscriber tester = new TestSubscriber(); 86 | 87 | Subject values = ReplaySubject.create(); 88 | values.subscribe(tester); 89 | values.onNext(0); 90 | values.onNext(1); 91 | values.onCompleted(); 92 | values.onNext(2); 93 | 94 | tester.assertReceivedOnNext(Arrays.asList(0,1)); 95 | tester.assertTerminalEvent(); 96 | tester.assertNoErrors(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter1/UnsubscribingExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter1; 24 | 25 | import static org.junit.Assert.assertFalse; 26 | import static org.junit.Assert.assertTrue; 27 | 28 | import java.util.Arrays; 29 | 30 | import org.junit.Test; 31 | 32 | import rx.Subscription; 33 | import rx.observers.TestSubscriber; 34 | import rx.subjects.ReplaySubject; 35 | import rx.subjects.Subject; 36 | import rx.subscriptions.Subscriptions; 37 | 38 | public class UnsubscribingExample { 39 | 40 | public void exampleUnsubscribe() { 41 | Subject values = ReplaySubject.create(); 42 | Subscription subscription = values.subscribe( 43 | v -> System.out.println(v), 44 | e -> System.err.println(e), 45 | () -> System.out.println("Done")); 46 | values.onNext(0); 47 | values.onNext(1); 48 | subscription.unsubscribe(); 49 | values.onNext(2); 50 | 51 | // 0 52 | // 1 53 | } 54 | 55 | public void exampleIndependentSubscriptions() { 56 | Subject values = ReplaySubject.create(); 57 | Subscription subscription1 = values.subscribe(v -> System.out 58 | .println("First: " + v)); 59 | values.subscribe(v -> System.out.println("Second: " + v)); 60 | values.onNext(0); 61 | values.onNext(1); 62 | subscription1.unsubscribe(); 63 | System.out.println("Unsubscribed first"); 64 | values.onNext(2); 65 | 66 | // First: 0 67 | // Second: 0 68 | // First: 1 69 | // Second: 1 70 | // Unsubscribed first 71 | // Second: 2 72 | } 73 | 74 | public void exampleUnsubscribeAction() { 75 | Subscription s = Subscriptions 76 | .create(() -> System.out.println("Clean")); 77 | s.unsubscribe(); 78 | 79 | // Clean 80 | } 81 | 82 | 83 | // 84 | // Tests 85 | // 86 | 87 | @Test 88 | public void testUnsubscribe() { 89 | TestSubscriber tester = new TestSubscriber(); 90 | 91 | Subject values = ReplaySubject.create(); 92 | Subscription subscription = values.subscribe(tester); 93 | values.onNext(0); 94 | values.onNext(1); 95 | subscription.unsubscribe(); 96 | values.onNext(2); 97 | 98 | tester.assertReceivedOnNext(Arrays.asList(0, 1)); 99 | tester.assertUnsubscribed(); 100 | } 101 | 102 | @Test 103 | public void testIndependentSubscriptions() { 104 | TestSubscriber tester1 = new TestSubscriber(); 105 | TestSubscriber tester2 = new TestSubscriber(); 106 | 107 | Subject values = ReplaySubject.create(); 108 | Subscription subscription1 = values.subscribe(tester1); 109 | Subscription subscription2 = values.subscribe(tester2); 110 | values.onNext(0); 111 | values.onNext(1); 112 | subscription1.unsubscribe(); 113 | values.onNext(2); 114 | 115 | tester1.assertReceivedOnNext(Arrays.asList(0, 1)); 116 | tester2.assertReceivedOnNext(Arrays.asList(0, 1, 2)); 117 | tester1.assertUnsubscribed(); 118 | assertFalse(tester2.isUnsubscribed()); 119 | 120 | subscription2.unsubscribe(); 121 | } 122 | 123 | @Test 124 | public void testUnsubscribeAction() { 125 | boolean[] ran = { false }; 126 | 127 | Subscription s = Subscriptions.create(() -> ran[0] = true); 128 | s.unsubscribe(); 129 | 130 | assertTrue(ran[0]); 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/CollectExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class CollectExample { 35 | 36 | public void example() { 37 | Observable values = Observable.range(10,5); 38 | 39 | values 40 | .collect( 41 | () -> new ArrayList(), 42 | (acc, value) -> acc.add(value)) 43 | .subscribe(v -> System.out.println(v)); 44 | 45 | // [10, 11, 12, 13, 14] 46 | } 47 | 48 | @Test 49 | public void test() { 50 | TestSubscriber> tester = new TestSubscriber<>(); 51 | 52 | Observable values = Observable.range(10,5); 53 | 54 | values 55 | .collect( 56 | () -> new ArrayList(), 57 | (acc, value) -> acc.add(value)) 58 | .subscribe(tester); 59 | 60 | tester.assertReceivedOnNext(Arrays.asList( 61 | Arrays.asList(10, 11, 12, 13, 14) 62 | )); 63 | tester.assertTerminalEvent(); 64 | tester.assertNoErrors(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/CountExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.observers.TestSubscriber; 32 | 33 | public class CountExample { 34 | 35 | private class PrintSubscriber extends Subscriber{ 36 | private final String name; 37 | public PrintSubscriber(String name) { 38 | this.name = name; 39 | } 40 | @Override 41 | public void onCompleted() { 42 | System.out.println(name + ": Completed"); 43 | } 44 | @Override 45 | public void onError(Throwable e) { 46 | System.out.println(name + ": Error: " + e); 47 | } 48 | @Override 49 | public void onNext(Object v) { 50 | System.out.println(name + ": " + v); 51 | } 52 | } 53 | 54 | 55 | public void example() { 56 | Observable values = Observable.range(0, 3); 57 | 58 | values 59 | .subscribe(new PrintSubscriber("Values")); 60 | values 61 | .count() 62 | .subscribe(new PrintSubscriber("Count")); 63 | 64 | // Values: 0 65 | // Values: 1 66 | // Values: 2 67 | // Values: Completed 68 | // Count: 3 69 | // Count: Completed 70 | } 71 | 72 | public void exampleCountLong() { 73 | Observable values = Observable.range(0, 3); 74 | 75 | values 76 | .subscribe(new PrintSubscriber("Values")); 77 | values 78 | .countLong() 79 | .subscribe(new PrintSubscriber("Count")); 80 | 81 | // Values: 0 82 | // Values: 1 83 | // Values: 2 84 | // Values: Completed 85 | // Count: 3 86 | // Count: Completed 87 | } 88 | 89 | 90 | // 91 | // Tests 92 | // 93 | 94 | @Test 95 | public void test() { 96 | TestSubscriber testerSource = new TestSubscriber<>(); 97 | TestSubscriber testerCount = new TestSubscriber<>(); 98 | 99 | Observable values = Observable.range(0, 3); 100 | 101 | values 102 | .subscribe(testerSource); 103 | values 104 | .count() 105 | .subscribe(testerCount); 106 | 107 | testerSource.assertReceivedOnNext(Arrays.asList(0,1,2)); 108 | testerSource.assertTerminalEvent(); 109 | testerSource.assertNoErrors(); 110 | 111 | testerCount.assertReceivedOnNext(Arrays.asList(3)); 112 | testerCount.assertTerminalEvent(); 113 | testerCount.assertNoErrors(); 114 | } 115 | 116 | @Test 117 | public void testCountLong() { 118 | TestSubscriber testerSource = new TestSubscriber<>(); 119 | TestSubscriber testerCount = new TestSubscriber<>(); 120 | 121 | Observable values = Observable.range(0, 3); 122 | 123 | values 124 | .subscribe(testerSource); 125 | values 126 | .countLong() 127 | .subscribe(testerCount); 128 | 129 | testerSource.assertReceivedOnNext(Arrays.asList(0,1,2)); 130 | testerSource.assertTerminalEvent(); 131 | testerSource.assertNoErrors(); 132 | 133 | testerCount.assertReceivedOnNext(Arrays.asList(3L)); 134 | testerCount.assertTerminalEvent(); 135 | testerCount.assertNoErrors(); 136 | } 137 | 138 | 139 | 140 | } 141 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/GroupByExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class GroupByExample { 33 | 34 | public void exampleGroupBy() { 35 | Observable values = Observable.just( 36 | "first", 37 | "second", 38 | "third", 39 | "forth", 40 | "fifth", 41 | "sixth" 42 | ); 43 | 44 | values.groupBy(word -> word.charAt(0)) 45 | .flatMap(group -> 46 | group.last().map(v -> group.getKey() + ": " + v) 47 | ) 48 | .subscribe(v -> System.out.println(v)); 49 | 50 | // s: sixth 51 | // t: third 52 | // f: fifth 53 | } 54 | 55 | 56 | // 57 | // Tests 58 | // 59 | 60 | @Test 61 | public void testGroupBy() { 62 | TestSubscriber tester = new TestSubscriber<>(); 63 | 64 | Observable values = Observable.just( 65 | "first", 66 | "second", 67 | "third", 68 | "forth", 69 | "fifth", 70 | "sixth" 71 | ); 72 | 73 | values.groupBy(word -> word.charAt(0)) 74 | .flatMap(group -> 75 | group.last().map(v -> group.getKey() + ": " + v) 76 | ) 77 | .subscribe(tester); 78 | 79 | tester.assertReceivedOnNext(Arrays.asList("s: sixth", "t: third", "f: fifth")); 80 | tester.assertTerminalEvent(); 81 | tester.assertNoErrors(); 82 | } 83 | } 84 | 85 | 86 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/LastExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.observers.TestSubscriber; 32 | 33 | public class LastExample { 34 | 35 | private class PrintSubscriber extends Subscriber{ 36 | private final String name; 37 | public PrintSubscriber(String name) { 38 | this.name = name; 39 | } 40 | @Override 41 | public void onCompleted() { 42 | System.out.println(name + ": Completed"); 43 | } 44 | @Override 45 | public void onError(Throwable e) { 46 | System.out.println(name + ": Error: " + e); 47 | } 48 | @Override 49 | public void onNext(Object v) { 50 | System.out.println(name + ": " + v); 51 | } 52 | } 53 | 54 | public void exampleLast() { 55 | Observable values = Observable.range(0,10); 56 | 57 | values 58 | .last() 59 | .subscribe(new PrintSubscriber("Last")); 60 | 61 | // 9 62 | } 63 | 64 | public void exampleLastWithPredicate() { 65 | Observable values = Observable.range(0,10); 66 | 67 | values 68 | .last(v -> v<5) 69 | .subscribe(new PrintSubscriber("Last")); 70 | 71 | // 4 72 | } 73 | 74 | public void exampleLastOrDefault() { 75 | Observable values = Observable.empty(); 76 | 77 | values 78 | .lastOrDefault(-1) 79 | .subscribe(new PrintSubscriber("Last")); 80 | 81 | // -1 82 | } 83 | 84 | public void exampleLastOrDefaultWithPredicate() { 85 | Observable values = Observable.empty(); 86 | 87 | values 88 | .lastOrDefault(-1, v -> v>5) 89 | .subscribe(new PrintSubscriber("Last")); 90 | 91 | // -1 92 | } 93 | 94 | 95 | // 96 | // Tests 97 | // 98 | 99 | @Test 100 | public void testLast() { 101 | TestSubscriber tester = new TestSubscriber<>(); 102 | 103 | Observable values = Observable.range(0,10); 104 | 105 | values 106 | .last() 107 | .subscribe(tester); 108 | 109 | tester.assertReceivedOnNext(Arrays.asList(9)); 110 | tester.assertTerminalEvent(); 111 | tester.assertNoErrors(); 112 | } 113 | 114 | @Test 115 | public void testLastWithPredicate() { 116 | TestSubscriber tester = new TestSubscriber<>(); 117 | 118 | Observable values = Observable.range(0,10); 119 | 120 | values 121 | .last(v -> v<5) 122 | .subscribe(tester); 123 | 124 | tester.assertReceivedOnNext(Arrays.asList(4)); 125 | tester.assertTerminalEvent(); 126 | tester.assertNoErrors(); 127 | } 128 | 129 | @Test 130 | public void testLastOrDefault() { 131 | TestSubscriber tester = new TestSubscriber<>(); 132 | 133 | Observable values = Observable.empty(); 134 | 135 | values 136 | .lastOrDefault(-1) 137 | .subscribe(tester); 138 | 139 | tester.assertReceivedOnNext(Arrays.asList(-1)); 140 | tester.assertTerminalEvent(); 141 | tester.assertNoErrors(); 142 | } 143 | 144 | @Test 145 | public void testLastOrDefaultWithPredicate() { 146 | TestSubscriber tester = new TestSubscriber<>(); 147 | 148 | Observable values = Observable.empty(); 149 | 150 | values 151 | .lastOrDefault(-1, v -> v<5) 152 | .subscribe(tester); 153 | 154 | tester.assertReceivedOnNext(Arrays.asList(-1)); 155 | tester.assertTerminalEvent(); 156 | tester.assertNoErrors(); 157 | } 158 | 159 | } 160 | 161 | 162 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/NestExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class NestExample { 33 | 34 | public void example() { 35 | Observable.range(0, 3) 36 | .nest() 37 | .subscribe(ob -> ob.subscribe(System.out::println)); 38 | 39 | // 0 40 | // 1 41 | // 2 42 | } 43 | 44 | 45 | // 46 | // Test 47 | // 48 | 49 | @Test 50 | public void test() { 51 | TestSubscriber tester = new TestSubscriber<>(); 52 | 53 | Observable.range(0, 3) 54 | .nest() 55 | .subscribe(ob -> ob.subscribe(tester)); 56 | 57 | tester.assertReceivedOnNext(Arrays.asList(0,1,2)); 58 | tester.assertTerminalEvent(); 59 | tester.assertNoErrors(); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/ReduceExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.observers.TestSubscriber; 32 | 33 | public class ReduceExample { 34 | 35 | private class PrintSubscriber extends Subscriber{ 36 | private final String name; 37 | public PrintSubscriber(String name) { 38 | this.name = name; 39 | } 40 | @Override 41 | public void onCompleted() { 42 | System.out.println(name + ": Completed"); 43 | } 44 | @Override 45 | public void onError(Throwable e) { 46 | System.out.println(name + ": Error: " + e); 47 | } 48 | @Override 49 | public void onNext(Object v) { 50 | System.out.println(name + ": " + v); 51 | } 52 | } 53 | 54 | 55 | public void example() { 56 | Observable values = Observable.range(0,5); 57 | 58 | values 59 | .reduce((i1,i2) -> i1+i2) 60 | .subscribe(new PrintSubscriber("Sum")); 61 | values 62 | .reduce((i1,i2) -> (i1>i2) ? i2 : i1) 63 | .subscribe(new PrintSubscriber("Min")); 64 | 65 | // Sum: 10 66 | // Sum: Completed 67 | // Min: 0 68 | // Min: Completed 69 | } 70 | 71 | public void exampleWithAccumulator() { 72 | Observable values = Observable.just("Rx", "is", "easy"); 73 | 74 | values 75 | .reduce(0, (acc,next) -> acc + 1) 76 | .subscribe(new PrintSubscriber("Count")); 77 | 78 | // Count: 3 79 | // Count: Completed 80 | } 81 | 82 | 83 | // 84 | // Tests 85 | // 86 | 87 | @Test 88 | public void test() { 89 | TestSubscriber testerSum = new TestSubscriber<>(); 90 | TestSubscriber testerMin = new TestSubscriber<>(); 91 | 92 | Observable values = Observable.range(0,5); 93 | 94 | values 95 | .reduce((i1,i2) -> i1+i2) 96 | .subscribe(testerSum); 97 | values 98 | .reduce((i1,i2) -> (i1>i2) ? i2 : i1) 99 | .subscribe(testerMin); 100 | 101 | testerSum.assertReceivedOnNext(Arrays.asList(10)); 102 | testerSum.assertTerminalEvent(); 103 | testerSum.assertNoErrors(); 104 | testerMin.assertReceivedOnNext(Arrays.asList(0)); 105 | testerMin.assertTerminalEvent(); 106 | testerMin.assertNoErrors(); 107 | } 108 | 109 | @Test 110 | public void testWithAccumulator() { 111 | TestSubscriber tester = new TestSubscriber<>(); 112 | 113 | Observable values = Observable.just("Rx", "is", "easy"); 114 | 115 | values 116 | .reduce(0, (acc,next) -> acc + 1) 117 | .subscribe(tester); 118 | 119 | tester.assertReceivedOnNext(Arrays.asList(3)); 120 | tester.assertTerminalEvent(); 121 | tester.assertNoErrors(); 122 | } 123 | 124 | } 125 | 126 | 127 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/ScanExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.observers.TestSubscriber; 32 | import rx.subjects.ReplaySubject; 33 | import rx.subjects.Subject; 34 | 35 | public class ScanExample { 36 | 37 | private class PrintSubscriber extends Subscriber{ 38 | private final String name; 39 | public PrintSubscriber(String name) { 40 | this.name = name; 41 | } 42 | @Override 43 | public void onCompleted() { 44 | System.out.println(name + ": Completed"); 45 | } 46 | @Override 47 | public void onError(Throwable e) { 48 | System.out.println(name + ": Error: " + e); 49 | } 50 | @Override 51 | public void onNext(Object v) { 52 | System.out.println(name + ": " + v); 53 | } 54 | } 55 | 56 | 57 | public void exampleRunningSum() { 58 | Observable values = Observable.range(0,5); 59 | 60 | values 61 | .scan((i1,i2) -> i1+i2) 62 | .subscribe(new PrintSubscriber("Sum")); 63 | 64 | // Sum: 0 65 | // Sum: 1 66 | // Sum: 3 67 | // Sum: 6 68 | // Sum: 10 69 | // Sum: Completed 70 | } 71 | 72 | public void exampleRunningMin() { 73 | Subject values = ReplaySubject.create(); 74 | 75 | values 76 | .subscribe(new PrintSubscriber("Values")); 77 | values 78 | .scan((i1,i2) -> (i1 tester = new TestSubscriber<>(); 106 | 107 | Observable values = Observable.range(0,5); 108 | 109 | values 110 | .scan((i1,i2) -> i1+i2) 111 | .subscribe(tester); 112 | 113 | tester.assertReceivedOnNext(Arrays.asList(0,1,3,6,10)); 114 | tester.assertTerminalEvent(); 115 | tester.assertNoErrors(); 116 | } 117 | 118 | @Test 119 | public void testRunningMin() { 120 | TestSubscriber testerSource = new TestSubscriber<>(); 121 | TestSubscriber testerScan = new TestSubscriber<>(); 122 | 123 | Subject values = ReplaySubject.create(); 124 | 125 | values 126 | .subscribe(testerSource); 127 | values 128 | .scan((i1,i2) -> (i1{ 42 | private final String name; 43 | public PrintSubscriber(String name) { 44 | this.name = name; 45 | } 46 | @Override 47 | public void onCompleted() { 48 | System.out.println(name + ": Completed"); 49 | } 50 | @Override 51 | public void onError(Throwable e) { 52 | System.out.println(name + ": Error: " + e); 53 | } 54 | @Override 55 | public void onNext(Object v) { 56 | System.out.println(name + ": " + v); 57 | } 58 | } 59 | 60 | public void exampleSingle() { 61 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 62 | 63 | values.take(10) 64 | .single(v -> v == 5L) // Emits a result 65 | .subscribe(new PrintSubscriber("Single1")); 66 | values 67 | .single(v -> v == 5L) // Never emits 68 | .subscribe(new PrintSubscriber("Single2")); 69 | 70 | // Single1: 5 71 | // Single1: Completed 72 | } 73 | 74 | public void exampleSingleOrDefault() { 75 | Observable values = Observable.empty(); 76 | 77 | values 78 | .singleOrDefault(-1) 79 | .subscribe(new PrintSubscriber("SingleOrDefault")); 80 | 81 | // SingleOrDefault: -1 82 | // SingleOrDefault: Completed 83 | } 84 | 85 | 86 | // 87 | // Tests 88 | // 89 | 90 | @Test 91 | public void testSingle() { 92 | TestSubscriber tester1 = new TestSubscriber<>(); 93 | TestSubscriber tester2 = new TestSubscriber<>(); 94 | TestScheduler scheduler = Schedulers.test(); 95 | 96 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 97 | 98 | Subscription s1 = values.take(10) 99 | .single(v -> v == 5L) // Emits a result 100 | .subscribe(tester1); 101 | Subscription s2 = values 102 | .single(v -> v == 5L) // Never emits 103 | .subscribe(tester2); 104 | 105 | scheduler.advanceTimeBy(2, TimeUnit.SECONDS); 106 | 107 | tester1.assertReceivedOnNext(Arrays.asList(5L)); 108 | tester1.assertTerminalEvent(); 109 | tester1.assertNoErrors(); 110 | tester2.assertReceivedOnNext(Arrays.asList()); 111 | assertEquals(tester2.getOnCompletedEvents().size(), 0); 112 | tester2.assertNoErrors(); 113 | 114 | s1.unsubscribe(); 115 | s2.unsubscribe(); 116 | } 117 | 118 | @Test 119 | public void testSingleOrDefault() { 120 | TestSubscriber tester = new TestSubscriber<>(); 121 | 122 | Observable values = Observable.empty(); 123 | 124 | values 125 | .singleOrDefault(-1) 126 | .subscribe(tester); 127 | 128 | tester.assertReceivedOnNext(Arrays.asList(-1)); 129 | tester.assertTerminalEvent(); 130 | tester.assertNoErrors(); 131 | } 132 | } 133 | 134 | 135 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/aggregation/ToCollectionExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.aggregation; 24 | 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class ToCollectionExample { 35 | 36 | public void exampleCustom() { 37 | Observable values = Observable.range(10,5); 38 | 39 | values 40 | .reduce( 41 | new ArrayList(), 42 | (acc, value) -> { 43 | acc.add(value); 44 | return acc; 45 | }) 46 | .subscribe(v -> System.out.println(v)); 47 | 48 | // [10, 11, 12, 13, 14] 49 | } 50 | 51 | public void exampleToList() { 52 | Observable values = Observable.range(10,5); 53 | 54 | values 55 | .toList() 56 | .subscribe(v -> System.out.println(v)); 57 | 58 | // [10, 11, 12, 13, 14] 59 | } 60 | 61 | public void exampleToSortedList() { 62 | Observable values = Observable.range(10,5); 63 | 64 | values 65 | .toSortedList((i1,i2) -> i2 - i1) 66 | .subscribe(v -> System.out.println(v)); 67 | 68 | // [14, 13, 12, 11, 10] 69 | } 70 | 71 | 72 | // 73 | // Tests 74 | // 75 | 76 | @Test 77 | public void testCustom() { 78 | TestSubscriber> tester = new TestSubscriber<>(); 79 | 80 | Observable values = Observable.range(10,5); 81 | 82 | values 83 | .reduce( 84 | new ArrayList(), 85 | (acc, value) -> { 86 | acc.add(value); 87 | return acc; 88 | }) 89 | .subscribe(tester); 90 | 91 | tester.assertReceivedOnNext(Arrays.asList(Arrays.asList(10, 11, 12, 13, 14))); 92 | tester.assertTerminalEvent(); 93 | tester.assertNoErrors(); 94 | } 95 | 96 | @Test 97 | public void testToList() { 98 | TestSubscriber> tester = new TestSubscriber<>(); 99 | 100 | Observable values = Observable.range(10,5); 101 | 102 | values 103 | .toList() 104 | .subscribe(tester); 105 | 106 | tester.assertReceivedOnNext(Arrays.asList(Arrays.asList(10, 11, 12, 13, 14))); 107 | tester.assertTerminalEvent(); 108 | tester.assertNoErrors(); 109 | } 110 | 111 | @Test 112 | public void testToSortedList() { 113 | TestSubscriber> tester = new TestSubscriber<>(); 114 | 115 | Observable values = Observable.range(10,5); 116 | 117 | values 118 | .toSortedList((i1,i2) -> i2 - i1) 119 | .subscribe(tester); 120 | 121 | tester.assertReceivedOnNext(Arrays.asList(Arrays.asList(14, 13, 12, 11, 10))); 122 | tester.assertTerminalEvent(); 123 | tester.assertNoErrors(); 124 | } 125 | 126 | } 127 | 128 | 129 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/creating/FromExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.creating; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.FutureTask; 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class FromExample { 35 | 36 | public void exampleFromFuture() { 37 | FutureTask f = new FutureTask(() -> { 38 | Thread.sleep(2000); 39 | return 21; 40 | }); 41 | new Thread(f).start(); 42 | 43 | Observable values = Observable.from(f); 44 | 45 | values.subscribe( 46 | v -> System.out.println("Received: " + v), 47 | e -> System.out.println("Error: " + e), 48 | () -> System.out.println("Completed") 49 | ); 50 | 51 | // Received: 21 52 | // Completed 53 | } 54 | 55 | public void exampleFromFutureTimeout() { 56 | FutureTask f = new FutureTask(() -> { 57 | Thread.sleep(2000); 58 | return 21; 59 | }); 60 | new Thread(f).start(); 61 | 62 | Observable values = Observable.from(f, 1000, TimeUnit.MILLISECONDS); 63 | 64 | values.subscribe( 65 | v -> System.out.println("Received: " + v), 66 | e -> System.out.println("Error: " + e), 67 | () -> System.out.println("Completed") 68 | ); 69 | 70 | // Error: java.util.concurrent.TimeoutException 71 | } 72 | 73 | public void exampleFromArray() { 74 | Integer[] is = {1,2,3}; 75 | Observable values = Observable.from(is); 76 | values.subscribe( 77 | v -> System.out.println("Received: " + v), 78 | e -> System.out.println("Error: " + e), 79 | () -> System.out.println("Completed") 80 | ); 81 | 82 | // Received: 1 83 | // Received: 2 84 | // Received: 3 85 | // Completed 86 | } 87 | 88 | public void exampleFromIterable() { 89 | Iterable input = Arrays.asList(1,2,3); 90 | Observable values = Observable.from(input); 91 | values.subscribe( 92 | v -> System.out.println("Received: " + v), 93 | e -> System.out.println("Error: " + e), 94 | () -> System.out.println("Completed") 95 | ); 96 | 97 | // Received: 1 98 | // Received: 2 99 | // Received: 3 100 | // Completed 101 | } 102 | 103 | 104 | // 105 | // Tests 106 | // 107 | 108 | @Test 109 | public void testFromFuture() { 110 | TestSubscriber tester = new TestSubscriber(); 111 | 112 | FutureTask f = new FutureTask(() -> { 113 | return 21; 114 | }); 115 | new Thread(f).start(); 116 | 117 | Observable values = Observable.from(f); 118 | 119 | values.subscribe(tester); 120 | 121 | tester.assertReceivedOnNext(Arrays.asList(21)); 122 | tester.assertNoErrors(); 123 | tester.assertTerminalEvent(); 124 | } 125 | 126 | @Test 127 | public void testFromArray() { 128 | TestSubscriber tester = new TestSubscriber(); 129 | 130 | Integer[] input = {1,2,3}; 131 | Observable values = Observable.from(input); 132 | values.subscribe(tester); 133 | 134 | tester.assertReceivedOnNext(Arrays.asList(input)); 135 | tester.assertNoErrors(); 136 | tester.assertTerminalEvent(); 137 | } 138 | 139 | @Test 140 | public void testFromIterable() { 141 | TestSubscriber tester = new TestSubscriber(); 142 | 143 | Iterable input = Arrays.asList(1,2,3); 144 | Observable values = Observable.from(input); 145 | values.subscribe(tester); 146 | 147 | tester.assertReceivedOnNext(Arrays.asList(1,2,3)); 148 | tester.assertNoErrors(); 149 | tester.assertTerminalEvent(); 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/ContainsExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.Subscription; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class ContainsExample { 37 | 38 | public void exampleContains() { 39 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 40 | 41 | Subscription subscription = values 42 | .contains(4L) 43 | .subscribe( 44 | v -> System.out.println(v), 45 | e -> System.out.println("Error: " + e), 46 | () -> System.out.println("Completed") 47 | ); 48 | 49 | subscription.unsubscribe(); 50 | 51 | // true 52 | // Completed 53 | } 54 | 55 | 56 | // 57 | // Test 58 | // 59 | 60 | @Test 61 | public void test() { 62 | TestSubscriber tester = new TestSubscriber(); 63 | TestScheduler scheduler = Schedulers.test(); 64 | 65 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 66 | 67 | Subscription subscription = values 68 | .contains(4L) 69 | .subscribe(tester); 70 | 71 | scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); 72 | subscription.unsubscribe(); 73 | 74 | tester.assertReceivedOnNext(Arrays.asList(true)); 75 | tester.assertTerminalEvent(); 76 | tester.assertNoErrors(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/DefaultIfEmptyExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class DefaultIfEmptyExample { 35 | 36 | public void exampleDefaultIfEmpty() { 37 | Observable values = Observable.empty(); 38 | 39 | values 40 | .defaultIfEmpty(2) 41 | .subscribe( 42 | v -> System.out.println(v), 43 | e -> System.out.println("Error: " + e), 44 | () -> System.out.println("Completed") 45 | ); 46 | 47 | // 2 48 | // Completed 49 | } 50 | 51 | public void exampleDefaultIfEmptyError() { 52 | Observable values = Observable.error(new Exception()); 53 | 54 | values 55 | .defaultIfEmpty(2) 56 | .subscribe( 57 | v -> System.out.println(v), 58 | e -> System.out.println("Error: " + e), 59 | () -> System.out.println("Completed") 60 | ); 61 | 62 | // Error: java.lang.Exception 63 | } 64 | 65 | 66 | // 67 | // Tests 68 | // 69 | 70 | @Test 71 | public void testDefaultIfEmpty() { 72 | TestSubscriber tester = new TestSubscriber(); 73 | 74 | Observable values = Observable.empty(); 75 | 76 | values 77 | .defaultIfEmpty(2) 78 | .subscribe(tester); 79 | 80 | tester.assertReceivedOnNext(Arrays.asList(2)); 81 | tester.assertTerminalEvent(); 82 | tester.assertNoErrors(); 83 | } 84 | 85 | @Test 86 | public void testDefaultIfEmptyError() { 87 | TestSubscriber tester = new TestSubscriber(); 88 | 89 | Observable values = Observable.error(new Exception()); 90 | 91 | values 92 | .defaultIfEmpty(2) 93 | .subscribe(tester); 94 | 95 | tester.assertReceivedOnNext(Arrays.asList()); 96 | tester.assertTerminalEvent(); 97 | assertEquals(tester.getOnErrorEvents().size(), 1); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/ElementAtExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class ElementAtExample { 33 | 34 | public void exampleElementAt() { 35 | Observable values = Observable.range(100, 10); 36 | 37 | values 38 | .elementAt(2) 39 | .subscribe( 40 | v -> System.out.println(v), 41 | e -> System.out.println("Error: " + e), 42 | () -> System.out.println("Completed") 43 | ); 44 | 45 | // 102 46 | // Completed 47 | } 48 | 49 | public void exampleElementAtOrDefault() { 50 | Observable values = Observable.range(100, 10); 51 | 52 | values 53 | .elementAtOrDefault(22, 0) 54 | .subscribe( 55 | v -> System.out.println(v), 56 | e -> System.out.println("Error: " + e), 57 | () -> System.out.println("Completed") 58 | ); 59 | 60 | // 0 61 | // Completed 62 | } 63 | 64 | 65 | // 66 | // Tests 67 | // 68 | 69 | @Test 70 | public void testElementAt() { 71 | TestSubscriber tester = new TestSubscriber(); 72 | 73 | Observable values = Observable.range(100, 10); 74 | 75 | values 76 | .elementAt(2) 77 | .subscribe(tester); 78 | 79 | tester.assertReceivedOnNext(Arrays.asList(102)); 80 | tester.assertTerminalEvent(); 81 | tester.assertNoErrors(); 82 | } 83 | 84 | @Test 85 | public void testElementAtOrDefault() { 86 | TestSubscriber tester = new TestSubscriber(); 87 | 88 | Observable values = Observable.range(100, 10); 89 | 90 | values 91 | .elementAtOrDefault(22, 0) 92 | .subscribe(tester); 93 | 94 | tester.assertReceivedOnNext(Arrays.asList(0)); 95 | tester.assertTerminalEvent(); 96 | tester.assertNoErrors(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/ExistsExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class ExistsExample { 33 | 34 | public void exampleFalse() { 35 | Observable values = Observable.range(0, 2); 36 | 37 | values 38 | .exists(i -> i > 2) 39 | .subscribe( 40 | v -> System.out.println(v), 41 | e -> System.out.println("Error: " + e), 42 | () -> System.out.println("Completed") 43 | ); 44 | 45 | // false 46 | // Completed 47 | } 48 | 49 | public void exampleTrue() { 50 | Observable values = Observable.range(0, 4); 51 | 52 | values 53 | .exists(i -> i > 2) 54 | .subscribe( 55 | v -> System.out.println(v), 56 | e -> System.out.println("Error: " + e), 57 | () -> System.out.println("Completed") 58 | ); 59 | 60 | // true 61 | // Completed 62 | } 63 | 64 | 65 | // 66 | // Tests 67 | // 68 | 69 | @Test 70 | public void testFalse() { 71 | TestSubscriber tester = new TestSubscriber(); 72 | 73 | Observable values = Observable.range(0, 2); 74 | 75 | values 76 | .exists(i -> i > 2) 77 | .subscribe(tester); 78 | 79 | tester.assertReceivedOnNext(Arrays.asList(false)); 80 | tester.assertTerminalEvent(); 81 | tester.assertNoErrors(); 82 | } 83 | 84 | @Test 85 | public void testTrue() { 86 | TestSubscriber tester = new TestSubscriber(); 87 | 88 | Observable values = Observable.range(0, 4); 89 | 90 | values 91 | .exists(i -> i > 2) 92 | .subscribe(tester); 93 | 94 | tester.assertReceivedOnNext(Arrays.asList(true)); 95 | tester.assertTerminalEvent(); 96 | tester.assertNoErrors(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/IsEmptyExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.Subscription; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class IsEmptyExample { 37 | 38 | public void exampleIsEmpty() { 39 | Observable values = Observable.timer(1000, TimeUnit.MILLISECONDS); 40 | 41 | Subscription subscription = values 42 | .isEmpty() 43 | .subscribe( 44 | v -> System.out.println(v), 45 | e -> System.out.println("Error: " + e), 46 | () -> System.out.println("Completed") 47 | ); 48 | 49 | subscription.unsubscribe(); 50 | 51 | // false 52 | // Completed 53 | } 54 | 55 | 56 | // 57 | // Test 58 | // 59 | 60 | @Test 61 | public void testIsEmpty() { 62 | TestSubscriber tester = new TestSubscriber(); 63 | TestScheduler scheduler = Schedulers.test(); 64 | 65 | Observable values = Observable.timer(1000, TimeUnit.MILLISECONDS, scheduler); 66 | 67 | Subscription subscription = values 68 | .isEmpty() 69 | .subscribe(tester); 70 | 71 | scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); 72 | subscription.unsubscribe(); 73 | 74 | tester.assertReceivedOnNext(Arrays.asList(false)); 75 | tester.assertTerminalEvent(); 76 | tester.assertNoErrors(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/inspection/SequenceEqualExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.inspection; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class SequenceEqualExample { 35 | 36 | public void exampleSequenceEqualTrue() { 37 | Observable strings = Observable.just("1", "2", "3"); 38 | Observable ints = Observable.just(1, 2, 3); 39 | 40 | Observable.sequenceEqual(strings, ints, (s,i) -> s.equals(i.toString())) 41 | .subscribe( 42 | v -> System.out.println(v), 43 | e -> System.out.println("Error: " + e), 44 | () -> System.out.println("Completed") 45 | ); 46 | 47 | // true 48 | // Completed 49 | } 50 | 51 | public void exampleSequenceEqualFalse() { 52 | Observable strings = Observable.just("1", "2", "3"); 53 | Observable ints = Observable.just(1, 2, 3); 54 | 55 | Observable.sequenceEqual(strings, ints) 56 | .subscribe( 57 | v -> System.out.println(v), 58 | e -> System.out.println("Error: " + e), 59 | () -> System.out.println("Completed") 60 | ); 61 | 62 | // false 63 | // Completed 64 | } 65 | 66 | public void exampleSequenceEqualError() { 67 | Observable values = Observable.create(o -> { 68 | o.onNext(1); 69 | o.onNext(2); 70 | o.onError(new Exception()); 71 | }); 72 | 73 | Observable.sequenceEqual(values, values) 74 | .subscribe( 75 | v -> System.out.println(v), 76 | e -> System.out.println("Error: " + e), 77 | () -> System.out.println("Completed") 78 | ); 79 | 80 | // Error: java.lang.Exception 81 | } 82 | 83 | 84 | // 85 | // Tests 86 | // 87 | 88 | @Test 89 | public void testSequenceEqualTrue() { 90 | TestSubscriber tester = new TestSubscriber(); 91 | 92 | Observable strings = Observable.just("1", "2", "3"); 93 | Observable ints = Observable.just(1, 2, 3); 94 | 95 | Observable.sequenceEqual(strings, ints, (s,i) -> s.equals(i.toString())) 96 | .subscribe(tester); 97 | 98 | tester.assertReceivedOnNext(Arrays.asList(true)); 99 | tester.assertTerminalEvent(); 100 | tester.assertNoErrors(); 101 | } 102 | 103 | @Test 104 | public void testSequenceEqualFalse() { 105 | TestSubscriber tester = new TestSubscriber(); 106 | 107 | Observable strings = Observable.just("1", "2", "3"); 108 | Observable ints = Observable.just(1, 2, 3); 109 | 110 | Observable.sequenceEqual(strings, ints) 111 | .subscribe(tester); 112 | 113 | tester.assertReceivedOnNext(Arrays.asList(false)); 114 | tester.assertTerminalEvent(); 115 | tester.assertNoErrors(); 116 | } 117 | 118 | @Test 119 | public void testSequenceEqualError() { 120 | TestSubscriber tester = new TestSubscriber(); 121 | 122 | Observable values = Observable.create(o -> { 123 | o.onNext(1); 124 | o.onNext(2); 125 | o.onError(new Exception()); 126 | }); 127 | 128 | Observable.sequenceEqual(values, values) 129 | .subscribe(tester); 130 | 131 | tester.assertReceivedOnNext(Arrays.asList()); 132 | tester.assertTerminalEvent(); 133 | assertEquals(tester.getOnErrorEvents().size(), 1); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/reducing/FilterExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.reducing; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class FilterExample { 33 | 34 | 35 | public void example() { 36 | Observable values = Observable.range(0,10); 37 | values 38 | .filter(v -> v % 2 == 0) 39 | .subscribe( 40 | v -> System.out.println(v), 41 | e -> System.out.println("Error: " + e), 42 | () -> System.out.println("Completed") 43 | ); 44 | 45 | // 0 46 | // 2 47 | // 4 48 | // 6 49 | // 8 50 | // Completed 51 | } 52 | 53 | 54 | // 55 | // Test 56 | // 57 | 58 | @Test 59 | public void test() { 60 | TestSubscriber tester = new TestSubscriber(); 61 | 62 | Observable values = Observable.range(0,10); 63 | values 64 | .filter(v -> v % 2 == 0) 65 | .subscribe(tester); 66 | 67 | tester.assertReceivedOnNext(Arrays.asList(0,2,4,6,8)); 68 | tester.assertTerminalEvent(); 69 | tester.assertNoErrors(); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/reducing/IgnoreExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.reducing; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class IgnoreExample { 33 | 34 | public void exampleIgnoreElements() { 35 | Observable values = Observable.range(0, 10); 36 | 37 | values 38 | .ignoreElements() 39 | .subscribe( 40 | v -> System.out.println(v), 41 | e -> System.out.println("Error: " + e), 42 | () -> System.out.println("Completed") 43 | ); 44 | 45 | // Completed 46 | } 47 | 48 | 49 | // 50 | // Tests 51 | // 52 | 53 | @Test 54 | public void testIgnoreElements() { 55 | TestSubscriber tester = new TestSubscriber(); 56 | 57 | Observable values = Observable.range(0, 10); 58 | 59 | values 60 | .ignoreElements() 61 | .subscribe(tester); 62 | 63 | tester.assertReceivedOnNext(Arrays.asList()); 64 | tester.assertTerminalEvent(); 65 | tester.assertNoErrors(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/CastTypeOfExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.Subscriber; 33 | import rx.observers.TestSubscriber; 34 | 35 | public class CastTypeOfExample { 36 | 37 | private static class PrintSubscriber extends Subscriber{ 38 | private final String name; 39 | public PrintSubscriber(String name) { 40 | this.name = name; 41 | } 42 | @Override 43 | public void onCompleted() { 44 | System.out.println(name + ": Completed"); 45 | } 46 | @Override 47 | public void onError(Throwable e) { 48 | System.out.println(name + ": Error: " + e); 49 | } 50 | @Override 51 | public void onNext(Object v) { 52 | System.out.println(name + ": " + v); 53 | } 54 | } 55 | 56 | 57 | public void exampleCast() { 58 | Observable values = Observable.just(0, 1, 2, 3); 59 | 60 | values 61 | .cast(Integer.class) 62 | .subscribe(new PrintSubscriber("Map")); 63 | 64 | // Map: 0 65 | // Map: 1 66 | // Map: 2 67 | // Map: 3 68 | // Map: Completed 69 | } 70 | 71 | public void exampleCastFail() { 72 | Observable values = Observable.just(0, 1, 2, "3"); 73 | 74 | values 75 | .cast(Integer.class) 76 | .subscribe(new PrintSubscriber("Map")); 77 | 78 | // Map: 0 79 | // Map: 1 80 | // Map: 2 81 | // Map: Error: java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Integer 82 | } 83 | 84 | public void exampleTypeOf() { 85 | Observable values = Observable.just(0, 1, "2", 3); 86 | 87 | values 88 | .ofType(Integer.class) 89 | .subscribe(new PrintSubscriber("Map")); 90 | 91 | // Map: 0 92 | // Map: 1 93 | // Map: 3 94 | // Map: Completed 95 | } 96 | 97 | 98 | // 99 | // Tests 100 | // 101 | 102 | @Test 103 | public void testCast() { 104 | TestSubscriber tester = new TestSubscriber<>(); 105 | 106 | Observable values = Observable.just(0, 1, 2, 3); 107 | 108 | values 109 | .cast(Integer.class) 110 | .subscribe(tester); 111 | 112 | tester.assertReceivedOnNext(Arrays.asList(0,1,2,3)); 113 | tester.assertTerminalEvent(); 114 | tester.assertNoErrors(); 115 | } 116 | 117 | @Test 118 | public void testCastFail() { 119 | TestSubscriber tester = new TestSubscriber<>(); 120 | 121 | Observable values = Observable.just(0, 1, 2, "3"); 122 | 123 | values 124 | .cast(Integer.class) 125 | .subscribe(tester); 126 | 127 | tester.assertReceivedOnNext(Arrays.asList(0,1,2)); 128 | tester.assertTerminalEvent(); 129 | assertEquals(tester.getOnErrorEvents().size(), 1); // received 1 error 130 | } 131 | 132 | @Test 133 | public void testTypeOf() { 134 | TestSubscriber tester = new TestSubscriber<>(); 135 | 136 | Observable values = Observable.just(0, 1, "2", 3); 137 | 138 | values 139 | .ofType(Integer.class) 140 | .subscribe(tester); 141 | 142 | tester.assertReceivedOnNext(Arrays.asList(0,1,3)); 143 | tester.assertTerminalEvent(); 144 | tester.assertNoErrors(); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/ConcatMapExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class ConcatMapExample { 36 | 37 | public void exampleConcatMap() { 38 | Observable.just(100, 150) 39 | .concatMap(i -> 40 | Observable.interval(i, TimeUnit.MILLISECONDS) 41 | .map(v -> i) 42 | .take(3)) 43 | .subscribe( 44 | System.out::println, 45 | System.out::println, 46 | () -> System.out.println("Completed")); 47 | 48 | // 100 49 | // 100 50 | // 100 51 | // 150 52 | // 150 53 | // 150 54 | // Completed 55 | } 56 | 57 | 58 | // 59 | // Test 60 | // 61 | 62 | @Test 63 | public void testConcatMap() { 64 | TestSubscriber tester = new TestSubscriber<>(); 65 | TestScheduler scheduler = Schedulers.test(); 66 | 67 | Observable.just(100, 150) 68 | .concatMap(i -> 69 | Observable.interval(i, TimeUnit.MILLISECONDS, scheduler) 70 | .map(v -> i) 71 | .take(3) 72 | ) 73 | .subscribe(tester); 74 | 75 | scheduler.advanceTimeBy(750, TimeUnit.MILLISECONDS); 76 | tester.assertReceivedOnNext(Arrays.asList(100, 100, 100, 150, 150, 150)); 77 | tester.assertTerminalEvent(); 78 | tester.assertNoErrors(); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/FlatMapIterableExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import java.util.ArrayList; 26 | import java.util.Arrays; 27 | import java.util.Iterator; 28 | import java.util.List; 29 | 30 | import org.junit.Test; 31 | 32 | import rx.Observable; 33 | import rx.observers.TestSubscriber; 34 | 35 | public class FlatMapIterableExample { 36 | 37 | public static class Range implements Iterable { 38 | 39 | private static class RangeIterator implements Iterator { 40 | private int next; 41 | private final int end; 42 | 43 | RangeIterator(int start, int count) { 44 | this.next = start; 45 | this.end = start + count; 46 | } 47 | 48 | @Override 49 | public boolean hasNext() { 50 | return next < end; 51 | } 52 | 53 | @Override 54 | public Integer next() { 55 | return next++; 56 | } 57 | 58 | } 59 | 60 | private final int start; 61 | private final int count; 62 | 63 | public Range(int start, int count) { 64 | this.start = start; 65 | this.count = count; 66 | } 67 | 68 | @Override 69 | public Iterator iterator() { 70 | return new RangeIterator(start, count); 71 | } 72 | } 73 | 74 | public static Iterable range(int start, int count) { 75 | List list = new ArrayList<>(); 76 | for (int i=start ; i range(1, i)) 85 | .subscribe(System.out::println); 86 | 87 | // 1 88 | // 1 89 | // 2 90 | // 1 91 | // 2 92 | // 3 93 | } 94 | 95 | public void exampleFlatMapIterableWithSelector() { 96 | Observable.range(1, 3) 97 | .flatMapIterable( 98 | i -> range(1, i), 99 | (ori, rv) -> ori * rv) 100 | .subscribe(System.out::println); 101 | 102 | // 1 103 | // 2 104 | // 4 105 | // 3 106 | // 6 107 | // 9 108 | } 109 | 110 | public void exampleFlatMapLazyIterable() { 111 | Observable.range(1, 3) 112 | .flatMapIterable( 113 | i -> new Range(1, i), 114 | (ori, rv) -> ori * rv) 115 | .subscribe(System.out::println); 116 | 117 | // 1 118 | // 2 119 | // 4 120 | // 3 121 | // 6 122 | // 9 123 | } 124 | 125 | 126 | // 127 | // Test 128 | // 129 | 130 | @Test 131 | public void testFlatMapIterable() { 132 | TestSubscriber tester = new TestSubscriber<>(); 133 | 134 | Observable.range(1, 3) 135 | .flatMapIterable(i -> range(1, i)) 136 | .subscribe(tester); 137 | 138 | tester.assertReceivedOnNext(Arrays.asList(1,1,2,1,2,3)); 139 | tester.assertTerminalEvent(); 140 | tester.assertNoErrors(); 141 | } 142 | 143 | @Test 144 | public void testFlatMapIterableWithSelector() { 145 | TestSubscriber tester = new TestSubscriber<>(); 146 | 147 | Observable.range(1, 3) 148 | .flatMapIterable( 149 | i -> range(1, i), 150 | (ori, rv) -> ori * rv) 151 | .subscribe(tester); 152 | 153 | tester.assertReceivedOnNext(Arrays.asList(1,2,4,3,6,9)); 154 | tester.assertTerminalEvent(); 155 | tester.assertNoErrors(); 156 | } 157 | 158 | @Test 159 | public void testFlatMapLazyIterable() { 160 | TestSubscriber tester = new TestSubscriber<>(); 161 | 162 | Observable.range(1, 3) 163 | .flatMapIterable( 164 | i -> new Range(1, i), 165 | (ori, rv) -> ori * rv) 166 | .subscribe(tester); 167 | 168 | tester.assertReceivedOnNext(Arrays.asList(1,2,4,3,6,9)); 169 | tester.assertTerminalEvent(); 170 | tester.assertNoErrors(); 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/MapExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.observers.TestSubscriber; 32 | 33 | public class MapExample { 34 | 35 | private static class PrintSubscriber extends Subscriber{ 36 | private final String name; 37 | public PrintSubscriber(String name) { 38 | this.name = name; 39 | } 40 | @Override 41 | public void onCompleted() { 42 | System.out.println(name + ": Completed"); 43 | } 44 | @Override 45 | public void onError(Throwable e) { 46 | System.out.println(name + ": Error: " + e); 47 | } 48 | @Override 49 | public void onNext(Object v) { 50 | System.out.println(name + ": " + v); 51 | } 52 | } 53 | 54 | public void exampleMap() { 55 | Observable values = Observable.range(0,4); 56 | 57 | values 58 | .map(i -> i + 3) 59 | .subscribe(new PrintSubscriber("Map")); 60 | 61 | // Map: 3 62 | // Map: 4 63 | // Map: 5 64 | // Map: 6 65 | // Map: Completed 66 | } 67 | 68 | public void exampleMap2() { 69 | Observable values = 70 | Observable.just("0", "1", "2", "3") 71 | .map(Integer::parseInt); 72 | 73 | values.subscribe(new PrintSubscriber("Map")); 74 | 75 | // Map: 0 76 | // Map: 1 77 | // Map: 2 78 | // Map: 3 79 | // Map: Completed 80 | } 81 | 82 | 83 | // 84 | // Tests 85 | // 86 | 87 | @Test 88 | public void testMap() { 89 | TestSubscriber tester = new TestSubscriber<>(); 90 | 91 | Observable values = Observable.range(0,4); 92 | 93 | values 94 | .map(i -> i + 3) 95 | .subscribe(tester); 96 | 97 | tester.assertReceivedOnNext(Arrays.asList(3,4,5,6)); 98 | tester.assertTerminalEvent(); 99 | tester.assertNoErrors(); 100 | } 101 | 102 | @Test 103 | public void testMap2() { 104 | TestSubscriber tester = new TestSubscriber<>(); 105 | 106 | Observable values = 107 | Observable.just("0", "1", "2", "3") 108 | .map(Integer::parseInt); 109 | 110 | values.subscribe(tester); 111 | 112 | tester.assertReceivedOnNext(Arrays.asList(0,1,2,3)); 113 | tester.assertTerminalEvent(); 114 | tester.assertNoErrors(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/MaterializeExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Notification; 30 | import rx.Observable; 31 | import rx.Subscriber; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class MaterializeExample { 35 | 36 | private static class PrintSubscriber extends Subscriber{ 37 | private final String name; 38 | public PrintSubscriber(String name) { 39 | this.name = name; 40 | } 41 | @Override 42 | public void onCompleted() { 43 | System.out.println(name + ": Completed"); 44 | } 45 | @Override 46 | public void onError(Throwable e) { 47 | System.out.println(name + ": Error: " + e); 48 | } 49 | @Override 50 | public void onNext(Object v) { 51 | System.out.println(name + ": " + v); 52 | } 53 | } 54 | 55 | 56 | public void exampleMaterialize() { 57 | Observable values = Observable.range(0,3); 58 | 59 | values.take(3) 60 | .materialize() 61 | .subscribe(new PrintSubscriber("Materialize")); 62 | 63 | // Materialize: [rx.Notification@a4c802e9 OnNext 0] 64 | // Materialize: [rx.Notification@a4c802ea OnNext 1] 65 | // Materialize: [rx.Notification@a4c802eb OnNext 2] 66 | // Materialize: [rx.Notification@18d48ace OnCompleted] 67 | // Materialize: Completed 68 | } 69 | 70 | 71 | // 72 | // Tests 73 | // 74 | 75 | @Test 76 | public void testMaterialize() { 77 | TestSubscriber> tester = new TestSubscriber<>(); 78 | 79 | Observable values = Observable.range(0,3); 80 | 81 | values.take(3) 82 | .materialize() 83 | .subscribe(tester); 84 | 85 | tester.assertReceivedOnNext(Arrays.asList( 86 | Notification.createOnNext(0), 87 | Notification.createOnNext(1), 88 | Notification.createOnNext(2), 89 | Notification.createOnCompleted() 90 | )); 91 | tester.assertTerminalEvent(); 92 | tester.assertNoErrors(); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter2/transforming/TimestampTimeIntervalExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter2.transforming; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.Subscriber; 33 | import rx.observers.TestSubscriber; 34 | import rx.schedulers.Schedulers; 35 | import rx.schedulers.TestScheduler; 36 | import rx.schedulers.TimeInterval; 37 | import rx.schedulers.Timestamped; 38 | 39 | public class TimestampTimeIntervalExample { 40 | 41 | private static class PrintSubscriber extends Subscriber{ 42 | private final String name; 43 | public PrintSubscriber(String name) { 44 | this.name = name; 45 | } 46 | @Override 47 | public void onCompleted() { 48 | System.out.println(name + ": Completed"); 49 | } 50 | @Override 51 | public void onError(Throwable e) { 52 | System.out.println(name + ": Error: " + e); 53 | } 54 | @Override 55 | public void onNext(Object v) { 56 | System.out.println(name + ": " + v); 57 | } 58 | } 59 | 60 | public void exampleTimestamp() { 61 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 62 | 63 | values.take(3) 64 | .timestamp() 65 | .subscribe(new PrintSubscriber("Timestamp")); 66 | 67 | // Timestamp: Timestamped(timestampMillis = 1428611094943, value = 0) 68 | // Timestamp: Timestamped(timestampMillis = 1428611095037, value = 1) 69 | // Timestamp: Timestamped(timestampMillis = 1428611095136, value = 2) 70 | // Timestamp: Completed 71 | } 72 | 73 | public void exampleTimeInteval() { 74 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 75 | 76 | values.take(3) 77 | .timeInterval() 78 | .subscribe(new PrintSubscriber("TimeInterval")); 79 | 80 | // TimeInterval: TimeInterval [intervalInMilliseconds=131, value=0] 81 | // TimeInterval: TimeInterval [intervalInMilliseconds=75, value=1] 82 | // TimeInterval: TimeInterval [intervalInMilliseconds=100, value=2] 83 | // TimeInterval: Completed 84 | } 85 | 86 | 87 | // 88 | // Tests 89 | // 90 | 91 | @Test 92 | public void testTimestamp() { 93 | TestSubscriber> tester = new TestSubscriber<>(); 94 | TestScheduler scheduler = Schedulers.test(); 95 | 96 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 97 | 98 | values.take(3) 99 | .timestamp(scheduler) 100 | .subscribe(tester); 101 | 102 | scheduler.advanceTimeBy(1, TimeUnit.SECONDS); 103 | 104 | assertEquals(tester.getOnNextEvents().get(0).getTimestampMillis(), 100); 105 | assertEquals(tester.getOnNextEvents().get(1).getTimestampMillis(), 200); 106 | assertEquals(tester.getOnNextEvents().get(2).getTimestampMillis(), 300); 107 | tester.assertTerminalEvent(); 108 | tester.assertNoErrors(); 109 | } 110 | 111 | @Test 112 | public void testTimeInteval() { 113 | TestSubscriber> tester = new TestSubscriber<>(); 114 | TestScheduler scheduler = Schedulers.test(); 115 | 116 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 117 | 118 | values.take(3) 119 | .timeInterval(scheduler) 120 | .subscribe(tester); 121 | 122 | scheduler.advanceTimeBy(1, TimeUnit.SECONDS); 123 | 124 | assertEquals(tester.getOnNextEvents().get(0).getIntervalInMilliseconds(), 100); 125 | assertEquals(tester.getOnNextEvents().get(1).getIntervalInMilliseconds(), 100); 126 | assertEquals(tester.getOnNextEvents().get(2).getIntervalInMilliseconds(), 100); 127 | tester.assertTerminalEvent(); 128 | tester.assertNoErrors(); 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/AmbExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class AmbExample { 36 | 37 | public void exampleAmb() { 38 | Observable.amb( 39 | Observable.timer(100, TimeUnit.MILLISECONDS).map(i -> "First"), 40 | Observable.timer(50, TimeUnit.MILLISECONDS).map(i -> "Second")) 41 | .subscribe(System.out::println); 42 | 43 | // Second 44 | } 45 | 46 | public void exampleAmbWith() { 47 | Observable.timer(100, TimeUnit.MILLISECONDS).map(i -> "First") 48 | .ambWith(Observable.timer(50, TimeUnit.MILLISECONDS).map(i -> "Second")) 49 | .ambWith(Observable.timer(70, TimeUnit.MILLISECONDS).map(i -> "Third")) 50 | .subscribe(System.out::println); 51 | 52 | // Second 53 | } 54 | 55 | 56 | // 57 | // Test 58 | // 59 | 60 | @Test 61 | public void testAmb() { 62 | TestSubscriber tester = new TestSubscriber<>(); 63 | TestScheduler scheduler = Schedulers.test(); 64 | 65 | Observable.amb( 66 | Observable.timer(100, TimeUnit.MILLISECONDS, scheduler).map(i -> "First"), 67 | Observable.timer(50, TimeUnit.MILLISECONDS, scheduler).map(i -> "Second")) 68 | .subscribe(tester); 69 | 70 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 71 | tester.assertReceivedOnNext(Arrays.asList("Second")); 72 | tester.assertTerminalEvent(); 73 | tester.assertNoErrors(); 74 | } 75 | 76 | @Test 77 | public void testAmbWith() { 78 | TestSubscriber tester = new TestSubscriber<>(); 79 | TestScheduler scheduler = Schedulers.test(); 80 | 81 | Observable.timer(100, TimeUnit.MILLISECONDS, scheduler).map(i -> "First") 82 | .ambWith(Observable.timer(50, TimeUnit.MILLISECONDS, scheduler).map(i -> "Second")) 83 | .ambWith(Observable.timer(70, TimeUnit.MILLISECONDS, scheduler).map(i -> "Third")) 84 | .subscribe(tester); 85 | 86 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 87 | tester.assertReceivedOnNext(Arrays.asList("Second")); 88 | tester.assertTerminalEvent(); 89 | tester.assertNoErrors(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/CombineLatestExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class CombineLatestExample { 36 | 37 | public void example() { 38 | Observable.combineLatest( 39 | Observable.interval(100, TimeUnit.MILLISECONDS) 40 | .doOnNext(i -> System.out.println("Left emits")), 41 | Observable.interval(150, TimeUnit.MILLISECONDS) 42 | .doOnNext(i -> System.out.println("Right emits")), 43 | (i1,i2) -> i1 + " - " + i2 44 | ) 45 | .take(6) 46 | .subscribe(System.out::println); 47 | 48 | // Left emits 49 | // Right emits 50 | // 0 - 0 51 | // Left emits 52 | // 1 - 0 53 | // Left emits 54 | // 2 - 0 55 | // Right emits 56 | // 2 - 1 57 | // Left emits 58 | // 3 - 1 59 | // Right emits 60 | // 3 - 2 61 | } 62 | 63 | 64 | // 65 | // Test 66 | // 67 | 68 | @Test 69 | public void test() { 70 | TestScheduler scheduler = Schedulers.test(); 71 | TestSubscriber tester = new TestSubscriber<>(); 72 | 73 | Observable.combineLatest( 74 | Observable.interval(100, TimeUnit.MILLISECONDS, scheduler), 75 | Observable.interval(150, TimeUnit.MILLISECONDS, scheduler), 76 | (i1,i2) -> i1 + " - " + i2 77 | ) 78 | .subscribe(tester); 79 | 80 | scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); 81 | scheduler.advanceTimeTo(150, TimeUnit.MILLISECONDS); 82 | scheduler.advanceTimeTo(200, TimeUnit.MILLISECONDS); 83 | scheduler.advanceTimeTo(300, TimeUnit.MILLISECONDS); 84 | 85 | tester.assertReceivedOnNext(Arrays.asList( 86 | "0 - 0", 87 | "1 - 0", 88 | "1 - 1", 89 | "2 - 1" 90 | )); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/ConcatExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class ConcatExample { 33 | 34 | public void exampleConcat() { 35 | Observable seq1 = Observable.range(0, 3); 36 | Observable seq2 = Observable.range(10, 3); 37 | 38 | Observable.concat(seq1, seq2) 39 | .subscribe(System.out::println); 40 | 41 | // 0 42 | // 1 43 | // 2 44 | // 10 45 | // 11 46 | // 12 47 | } 48 | 49 | public void exampleConcatDynamic() { 50 | Observable words = Observable.just( 51 | "First", 52 | "Second", 53 | "Third", 54 | "Fourth", 55 | "Fifth", 56 | "Sixth" 57 | ); 58 | 59 | Observable.concat(words.groupBy(v -> v.charAt(0))) 60 | .subscribe(System.out::println); 61 | 62 | // First 63 | // Fourth 64 | // Fifth 65 | // Second 66 | // Sixth 67 | // Third 68 | } 69 | 70 | public void exampleConcatWith() { 71 | Observable seq1 = Observable.range(0, 3); 72 | Observable seq2 = Observable.range(10, 3); 73 | Observable seq3 = Observable.just(20); 74 | 75 | seq1.concatWith(seq2) 76 | .concatWith(seq3) 77 | .subscribe(System.out::println); 78 | 79 | // 0 80 | // 1 81 | // 2 82 | // 10 83 | // 11 84 | // 12 85 | // 20 86 | } 87 | 88 | 89 | // 90 | // Tests 91 | // 92 | 93 | @Test 94 | public void testConcat() { 95 | TestSubscriber tester = new TestSubscriber<>(); 96 | 97 | Observable seq1 = Observable.range(0, 3); 98 | Observable seq2 = Observable.range(10, 3); 99 | 100 | Observable.concat(seq1, seq2) 101 | .subscribe(tester); 102 | 103 | tester.assertReceivedOnNext(Arrays.asList(0,1,2,10,11,12)); 104 | tester.assertTerminalEvent(); 105 | tester.assertNoErrors(); 106 | } 107 | 108 | @Test 109 | public void testConcatDynamic() { 110 | TestSubscriber tester = new TestSubscriber<>(); 111 | 112 | Observable words = Observable.just( 113 | "First", 114 | "Second", 115 | "Third", 116 | "Fourth", 117 | "Fifth", 118 | "Sixth" 119 | ); 120 | 121 | Observable.concat(words.groupBy(v -> v.charAt(0))) 122 | .subscribe(tester); 123 | 124 | tester.assertReceivedOnNext(Arrays.asList( 125 | "First", 126 | "Fourth", 127 | "Fifth", 128 | "Second", 129 | "Sixth", 130 | "Third")); 131 | tester.assertTerminalEvent(); 132 | tester.assertNoErrors(); 133 | } 134 | 135 | @Test 136 | public void testConcatWith() { 137 | TestSubscriber tester = new TestSubscriber<>(); 138 | 139 | Observable seq1 = Observable.range(0, 3); 140 | Observable seq2 = Observable.range(10, 3); 141 | Observable seq3 = Observable.just(20); 142 | 143 | seq1.concatWith(seq2) 144 | .concatWith(seq3) 145 | .subscribe(tester); 146 | 147 | tester.assertReceivedOnNext(Arrays.asList(0,1,2,10,11,12,20)); 148 | tester.assertTerminalEvent(); 149 | tester.assertNoErrors(); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/MergeExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import static org.junit.Assert.assertTrue; 26 | 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.Subscription; 33 | import rx.observers.TestSubscriber; 34 | import rx.schedulers.Schedulers; 35 | import rx.schedulers.TestScheduler; 36 | 37 | public class MergeExample { 38 | 39 | public void example() { 40 | Observable.merge( 41 | Observable.interval(250, TimeUnit.MILLISECONDS).map(i -> "First"), 42 | Observable.interval(150, TimeUnit.MILLISECONDS).map(i -> "Second")) 43 | .take(10) 44 | .subscribe(System.out::println); 45 | 46 | // Second 47 | // First 48 | // Second 49 | // Second 50 | // First 51 | // Second 52 | // Second 53 | // First 54 | // Second 55 | // First 56 | } 57 | 58 | public void exampleMergeWith() { 59 | Observable.interval(250, TimeUnit.MILLISECONDS).map(i -> "First") 60 | .mergeWith(Observable.interval(150, TimeUnit.MILLISECONDS).map(i -> "Second")) 61 | .take(10) 62 | .subscribe(System.out::println); 63 | 64 | // Second 65 | // First 66 | // Second 67 | // Second 68 | // First 69 | // Second 70 | // First 71 | // Second 72 | // Second 73 | // First 74 | } 75 | 76 | 77 | // 78 | // Test 79 | // 80 | 81 | @Test 82 | public void test() { 83 | TestScheduler scheduler = Schedulers.test(); 84 | TestSubscriber tester = new TestSubscriber<>(); 85 | 86 | Subscription subscription = Observable.merge( 87 | Observable.interval(250, TimeUnit.MILLISECONDS, scheduler).map(i -> "First"), 88 | Observable.interval(150, TimeUnit.MILLISECONDS, scheduler).map(i -> "Second")) 89 | .take(10) 90 | .distinctUntilChanged() 91 | .subscribe(tester); 92 | 93 | // Each time that merge switches between the two sources, 94 | // distinctUntilChanged allows one more value through. 95 | // If more that 2 values comes through, merge is going back and forth 96 | scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); 97 | assertTrue(tester.getOnNextEvents().size() > 2); 98 | 99 | subscription.unsubscribe(); 100 | } 101 | 102 | @Test 103 | public void testMergeWith() { 104 | TestScheduler scheduler = Schedulers.test(); 105 | TestSubscriber tester = new TestSubscriber<>(); 106 | 107 | Subscription subscription = Observable.interval(250, TimeUnit.MILLISECONDS, scheduler).map(i -> "First") 108 | .mergeWith(Observable.interval(150, TimeUnit.MILLISECONDS, scheduler).map(i -> "Second")) 109 | .distinctUntilChanged() 110 | .subscribe(tester); 111 | 112 | // Each time that merge switches between the two sources, 113 | // distinctUntilChanged allows one more value through. 114 | // If more that 2 values comes through, merge is going back and forth 115 | scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); 116 | assertTrue(tester.getOnNextEvents().size() > 2); 117 | 118 | subscription.unsubscribe(); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/StartWithExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class StartWithExample { 33 | 34 | public void example() { 35 | Observable values = Observable.range(0, 3); 36 | 37 | values.startWith(-1,-2) 38 | .subscribe(System.out::println); 39 | 40 | // -1 41 | // -2 42 | // 0 43 | // 1 44 | // 2 45 | } 46 | 47 | 48 | // 49 | // Test 50 | // 51 | 52 | @Test 53 | public void test() { 54 | TestSubscriber tester = new TestSubscriber<>(); 55 | 56 | Observable values = Observable.range(0, 3); 57 | 58 | values.startWith(-1,-2) 59 | .subscribe(tester); 60 | 61 | tester.assertReceivedOnNext(Arrays.asList(-1,-2,0,1,2)); 62 | tester.assertTerminalEvent(); 63 | tester.assertNoErrors(); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/SwitchMapExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class SwitchMapExample { 36 | 37 | public void example() { 38 | Observable.interval(100, TimeUnit.MILLISECONDS) 39 | .switchMap(i -> 40 | Observable.interval(30, TimeUnit.MILLISECONDS) 41 | .map(l -> i)) 42 | .take(9) 43 | .subscribe(System.out::println); 44 | 45 | // 0 46 | // 0 47 | // 0 48 | // 1 49 | // 1 50 | // 1 51 | // 2 52 | // 2 53 | // 2 54 | } 55 | 56 | 57 | // 58 | // Test 59 | // 60 | 61 | @Test 62 | public void test() { 63 | TestSubscriber tester = new TestSubscriber<>(); 64 | TestScheduler scheduler = Schedulers.test(); 65 | 66 | Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 67 | .switchMap(i -> 68 | Observable.interval(30, TimeUnit.MILLISECONDS, scheduler) 69 | .map(l -> i)) 70 | .take(9) 71 | .distinctUntilChanged() 72 | .subscribe(tester); 73 | 74 | scheduler.advanceTimeBy(400, TimeUnit.MILLISECONDS); 75 | tester.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L)); 76 | tester.assertTerminalEvent(); 77 | tester.assertNoErrors(); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/combining/SwitchOnNextExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.combining; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Arrays; 28 | import java.util.concurrent.TimeUnit; 29 | 30 | import org.junit.Test; 31 | 32 | import rx.Observable; 33 | import rx.observers.TestSubscriber; 34 | import rx.schedulers.Schedulers; 35 | import rx.schedulers.TestScheduler; 36 | 37 | public class SwitchOnNextExample { 38 | 39 | public void example() { 40 | Observable.switchOnNext( 41 | Observable.interval(100, TimeUnit.MILLISECONDS) 42 | .map(i -> 43 | Observable.interval(30, TimeUnit.MILLISECONDS) 44 | .map(i2 -> i) 45 | ) 46 | ) 47 | .take(9) 48 | .subscribe(System.out::println); 49 | 50 | // 0 51 | // 0 52 | // 0 53 | // 1 54 | // 1 55 | // 1 56 | // 2 57 | // 2 58 | // 2 59 | } 60 | 61 | 62 | // 63 | // Test 64 | // 65 | 66 | @Test 67 | public void test() { 68 | TestSubscriber tester = new TestSubscriber<>(); 69 | TestScheduler scheduler = Schedulers.test(); 70 | 71 | Observable.switchOnNext( 72 | Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 73 | .map(i -> 74 | Observable.interval(30, TimeUnit.MILLISECONDS, scheduler) 75 | .map(i2 -> i) 76 | ) 77 | ) 78 | .distinctUntilChanged() 79 | .subscribe(tester); 80 | 81 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 82 | tester.assertReceivedOnNext(Arrays.asList(0L,1L,2L,3L)); 83 | tester.assertNoErrors(); 84 | assertEquals(tester.getOnCompletedEvents().size(), 0); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/custom/ComposeExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.custom; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class ComposeExample { 33 | 34 | /** 35 | * A custom operator for calculating a running average 36 | * 37 | * @author Chris 38 | * 39 | */ 40 | public static class RunningAverage implements Observable.Transformer { 41 | private static class AverageAcc { 42 | public final int sum; 43 | public final int count; 44 | public AverageAcc(int sum, int count) { 45 | this.sum = sum; 46 | this.count = count; 47 | } 48 | } 49 | 50 | final int threshold; 51 | 52 | public RunningAverage() { 53 | this.threshold = Integer.MAX_VALUE; 54 | } 55 | 56 | public RunningAverage(int threshold) { 57 | this.threshold = threshold; 58 | } 59 | 60 | @Override 61 | public Observable call(Observable source) { 62 | return source 63 | .filter(i -> i< this.threshold) 64 | .scan( 65 | new AverageAcc(0,0), 66 | (acc, v) -> new AverageAcc(acc.sum + v, acc.count + 1)) 67 | .filter(acc -> acc.count > 0) 68 | .map(acc -> acc.sum/(double)acc.count); 69 | } 70 | } 71 | 72 | public void exampleComposeFromClass() { 73 | Observable.just(2, 3, 10, 12, 4) 74 | .compose(new RunningAverage()) 75 | .subscribe(System.out::println); 76 | 77 | // 2.0 78 | // 2.5 79 | // 5.0 80 | // 6.75 81 | // 6.2 82 | } 83 | 84 | public void exampleComposeParameterised() { 85 | Observable.just(2, 3, 10, 12, 4) 86 | .compose(new RunningAverage(5)) 87 | .subscribe(System.out::println); 88 | 89 | // 2.0 90 | // 2.5 91 | // 3.0 92 | } 93 | 94 | 95 | // 96 | // Test 97 | // 98 | 99 | @Test 100 | public void testComposeFromClass() { 101 | TestSubscriber tester = new TestSubscriber<>(); 102 | 103 | Observable.just(2, 3, 10, 12, 4) 104 | .compose(new RunningAverage()) 105 | .subscribe(tester); 106 | 107 | tester.assertReceivedOnNext(Arrays.asList(2.0, 2.5, 5.0, 6.75, 6.2)); 108 | tester.assertTerminalEvent(); 109 | tester.assertNoErrors(); 110 | } 111 | 112 | @Test 113 | public void testComposeParameterised() { 114 | TestSubscriber tester = new TestSubscriber<>(); 115 | 116 | Observable.just(2, 3, 10, 12, 4) 117 | .compose(new RunningAverage(5)) 118 | .subscribe(tester); 119 | 120 | tester.assertReceivedOnNext(Arrays.asList(2.0, 2.5, 3.0)); 121 | tester.assertTerminalEvent(); 122 | tester.assertNoErrors(); 123 | } 124 | 125 | 126 | } 127 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/custom/LiftExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.custom; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.functions.Func1; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class LiftExample { 35 | 36 | public static class MyMap implements Observable.Operator { 37 | private Func1 transformer; 38 | 39 | public MyMap(Func1 transformer) { 40 | this.transformer = transformer; 41 | } 42 | 43 | @Override 44 | public Subscriber call(Subscriber subscriber) { 45 | return new Subscriber() { 46 | 47 | @Override 48 | public void onCompleted() { 49 | if (!subscriber.isUnsubscribed()) 50 | subscriber.onCompleted(); 51 | } 52 | 53 | @Override 54 | public void onError(Throwable e) { 55 | if (!subscriber.isUnsubscribed()) 56 | subscriber.onError(e); 57 | } 58 | 59 | @Override 60 | public void onNext(T t) { 61 | if (!subscriber.isUnsubscribed()) 62 | subscriber.onNext(transformer.call(t)); 63 | } 64 | 65 | }; 66 | } 67 | 68 | public static MyMap create(Func1 transformer) { 69 | return new MyMap(transformer); 70 | } 71 | } 72 | 73 | public void exampleLift() { 74 | Observable.range(0, 5) 75 | .lift(MyMap.create(i -> i + "!")) 76 | .subscribe(System.out::println); 77 | 78 | // 0! 79 | // 1! 80 | // 2! 81 | // 3! 82 | // 4! 83 | } 84 | 85 | 86 | // 87 | // Tests 88 | // 89 | 90 | @Test 91 | public void testLift() { 92 | TestSubscriber tester = new TestSubscriber<>(); 93 | 94 | Observable.range(0, 5) 95 | .lift(MyMap.create(i -> i + "!")) 96 | .subscribe(tester); 97 | 98 | tester.assertReceivedOnNext(Arrays.asList("0!", "1!", "2!", "3!", "4!")); 99 | tester.assertTerminalEvent(); 100 | tester.assertNoErrors(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/error/RetryExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.error; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Random; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class RetryExample { 35 | 36 | public void exampleRetry() { 37 | Random random = new Random(); 38 | Observable values = Observable.create(o -> { 39 | o.onNext(random.nextInt() % 20); 40 | o.onNext(random.nextInt() % 20); 41 | o.onError(new Exception()); 42 | }); 43 | 44 | values 45 | .retry(1) 46 | .subscribe(v -> System.out.println(v)); 47 | 48 | // 0 49 | // 13 50 | // 9 51 | // 15 52 | // java.lang.Exception 53 | } 54 | 55 | 56 | // 57 | // Test 58 | // 59 | 60 | @Test 61 | public void testRetry() { 62 | TestSubscriber tester = new TestSubscriber<>(); 63 | Random random = new Random(); 64 | Observable values = Observable.create(o -> { 65 | o.onNext(random.nextInt() % 20); 66 | o.onNext(random.nextInt() % 20); 67 | o.onError(new Exception()); 68 | }); 69 | 70 | values 71 | .retry(1) 72 | .subscribe(tester); 73 | 74 | assertEquals(tester.getOnNextEvents().size(), 4); 75 | tester.assertTerminalEvent(); 76 | assertEquals(tester.getOnErrorEvents().size(), 1); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/error/RetryWhenExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.error; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class RetryWhenExample { 36 | 37 | public void example() { 38 | Observable source = Observable.create(o -> { 39 | o.onNext(1); 40 | o.onNext(2); 41 | o.onError(new Exception("Failed")); 42 | }); 43 | 44 | source.retryWhen((o) -> o 45 | .take(2) 46 | .delay(100, TimeUnit.MILLISECONDS)) 47 | .timeInterval() 48 | .subscribe( 49 | System.out::println, 50 | System.out::println); 51 | 52 | // TimeInterval [intervalInMilliseconds=17, value=1] 53 | // TimeInterval [intervalInMilliseconds=0, value=2] 54 | // TimeInterval [intervalInMilliseconds=102, value=1] 55 | // TimeInterval [intervalInMilliseconds=0, value=2] 56 | // TimeInterval [intervalInMilliseconds=102, value=1] 57 | // TimeInterval [intervalInMilliseconds=0, value=2] 58 | } 59 | 60 | 61 | // 62 | // Test 63 | // 64 | 65 | @Test 66 | public void test() { 67 | TestScheduler scheduler = Schedulers.test(); 68 | TestSubscriber intervals = new TestSubscriber<>(); 69 | 70 | Observable source = Observable.create(o -> { 71 | o.onNext(1); 72 | o.onNext(2); 73 | o.onError(new Exception("Failed")); 74 | }); 75 | source.retryWhen((o) -> o 76 | .take(2) 77 | .delay(100, TimeUnit.MILLISECONDS, scheduler) 78 | , scheduler) 79 | .timeInterval(scheduler) 80 | .map(i -> i.getIntervalInMilliseconds()) 81 | .subscribe(intervals); 82 | 83 | scheduler.advanceTimeBy(200, TimeUnit.MILLISECONDS); 84 | intervals.assertReceivedOnNext(Arrays.asList(0L, 0L, 100L, 0L, 100L, 0L)); 85 | intervals.assertTerminalEvent(); 86 | intervals.assertNoErrors(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/error/UsingExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.error; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | 34 | public class UsingExample { 35 | 36 | public void exampleUsing() { 37 | Observable values = Observable.using( 38 | () -> { 39 | String resource = "MyResource"; 40 | System.out.println("Leased: " + resource); 41 | return resource; 42 | }, 43 | (resource) -> { 44 | return Observable.create(o -> { 45 | for (Character c : resource.toCharArray()) 46 | o.onNext(c); 47 | o.onCompleted(); 48 | }); 49 | }, 50 | (resource) -> System.out.println("Disposed: " + resource)); 51 | 52 | values 53 | .subscribe( 54 | v -> System.out.println(v), 55 | e -> System.out.println(e)); 56 | 57 | // Leased: MyResource 58 | // M 59 | // y 60 | // R 61 | // e 62 | // s 63 | // o 64 | // u 65 | // r 66 | // c 67 | // e 68 | // Disposed: MyResource 69 | } 70 | 71 | 72 | // 73 | // Test 74 | // 75 | 76 | @Test 77 | public void testUsing() { 78 | TestSubscriber tester = new TestSubscriber<>(); 79 | String[] leaseRelease = {"", ""}; 80 | 81 | Observable values = Observable.using( 82 | () -> { 83 | String resource = "MyResource"; 84 | leaseRelease[0] = resource; 85 | return resource; 86 | }, 87 | (resource) -> { 88 | return Observable.create(o -> { 89 | for (Character c : resource.toCharArray()) 90 | o.onNext(c); 91 | o.onCompleted(); 92 | }); 93 | }, 94 | (resource) -> leaseRelease[1] = resource); 95 | 96 | values 97 | .subscribe(tester); 98 | 99 | assertEquals(leaseRelease[0], leaseRelease[1]); 100 | tester.assertReceivedOnNext(Arrays.asList('M','y','R','e','s','o','u','r','c','e')); 101 | tester.assertTerminalEvent(); 102 | tester.assertNoErrors(); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/hotandcold/CacheExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.hotandcold; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.Subscription; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class CacheExample { 37 | 38 | public void exampleCache() throws InterruptedException { 39 | Observable obs = Observable.interval(100, TimeUnit.MILLISECONDS) 40 | .take(5) 41 | .cache(); 42 | 43 | Thread.sleep(500); 44 | obs.subscribe(i -> System.out.println("First: " + i)); 45 | Thread.sleep(300); 46 | obs.subscribe(i -> System.out.println("Second: " + i)); 47 | 48 | // First: 0 49 | // First: 1 50 | // First: 2 51 | // Second: 0 52 | // Second: 1 53 | // Second: 2 54 | // First: 3 55 | // Second: 3 56 | // First: 4 57 | // Second: 4 58 | } 59 | 60 | public void exampleCacheUnsubscribe() throws InterruptedException { 61 | Observable obs = Observable.interval(100, TimeUnit.MILLISECONDS) 62 | .take(5) 63 | .doOnNext(System.out::println) 64 | .cache() 65 | .doOnSubscribe(() -> System.out.println("Subscribed")) 66 | .doOnUnsubscribe(() -> System.out.println("Unsubscribed")); 67 | 68 | Subscription subscription = obs.subscribe(); 69 | Thread.sleep(150); 70 | subscription.unsubscribe(); 71 | 72 | // Subscribed 73 | // 0 74 | // Unsubscribed 75 | // 1 76 | // 2 77 | // 3 78 | // 4 79 | } 80 | 81 | 82 | // 83 | // Tests 84 | // 85 | 86 | @Test 87 | public void testCache() throws InterruptedException { 88 | TestSubscriber tester1 = new TestSubscriber(); 89 | TestSubscriber tester2 = new TestSubscriber(); 90 | TestScheduler scheduler = Schedulers.test(); 91 | 92 | Observable obs = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 93 | .take(5) 94 | .cache(); 95 | 96 | tester1.assertReceivedOnNext(Arrays.asList()); 97 | tester2.assertReceivedOnNext(Arrays.asList()); 98 | 99 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 100 | obs.subscribe(tester1); 101 | tester1.assertReceivedOnNext(Arrays.asList()); 102 | tester2.assertReceivedOnNext(Arrays.asList()); 103 | 104 | scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS); 105 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L)); 106 | tester2.assertReceivedOnNext(Arrays.asList()); 107 | 108 | obs.subscribe(tester2); 109 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L)); 110 | tester2.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L)); 111 | 112 | scheduler.advanceTimeBy(200, TimeUnit.MILLISECONDS); 113 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 114 | tester2.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 115 | } 116 | 117 | @Test 118 | public void testCacheUnsubscribe() throws InterruptedException { 119 | TestSubscriber tester = new TestSubscriber(); 120 | TestScheduler scheduler = Schedulers.test(); 121 | 122 | Observable obs = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 123 | .take(5) 124 | .doOnEach(tester) 125 | .cache(); 126 | 127 | Subscription subscription = obs.subscribe(); 128 | scheduler.advanceTimeBy(150, TimeUnit.MILLISECONDS); 129 | tester.assertReceivedOnNext(Arrays.asList(0L)); 130 | 131 | subscription.unsubscribe(); 132 | scheduler.advanceTimeBy(350, TimeUnit.MILLISECONDS); 133 | tester.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/hotandcold/ColdExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.hotandcold; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class ColdExample { 36 | 37 | public void example() throws InterruptedException { 38 | Observable cold = 39 | Observable 40 | .interval(200, TimeUnit.MILLISECONDS) 41 | .take(5); 42 | 43 | cold.subscribe(i -> System.out.println("First: " + i)); 44 | Thread.sleep(500); 45 | cold.subscribe(i -> System.out.println("Second: " + i)); 46 | 47 | // First: 0 48 | // First: 1 49 | // First: 2 50 | // Second: 0 51 | // First: 3 52 | // Second: 1 53 | // First: 4 54 | // Second: 2 55 | // Second: 3 56 | // Second: 4 57 | } 58 | 59 | 60 | // 61 | // Test 62 | // 63 | 64 | @Test 65 | public void test() { 66 | TestScheduler scheduler = Schedulers.test(); 67 | TestSubscriber tester1 = new TestSubscriber<>(); 68 | TestSubscriber tester2 = new TestSubscriber<>(); 69 | 70 | Observable cold = 71 | Observable 72 | .interval(200, TimeUnit.MILLISECONDS, scheduler) 73 | .take(5); 74 | 75 | cold.subscribe(tester1); 76 | tester1.assertReceivedOnNext(Arrays.asList()); 77 | tester2.assertReceivedOnNext(Arrays.asList()); 78 | 79 | scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); 80 | cold.subscribe(tester2); 81 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L)); 82 | tester2.assertReceivedOnNext(Arrays.asList()); 83 | 84 | scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); 85 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 86 | tester2.assertReceivedOnNext(Arrays.asList(0L, 1L)); 87 | 88 | scheduler.advanceTimeTo(1500, TimeUnit.MILLISECONDS); 89 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 90 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/hotandcold/MulticastExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.hotandcold; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.Subscription; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class MulticastExample { 37 | 38 | public void exampleMutlicast() throws InterruptedException { 39 | Observable cold = 40 | Observable 41 | .interval(200, TimeUnit.MILLISECONDS) 42 | .publish() 43 | .refCount(); 44 | 45 | Subscription s1 = cold.subscribe(i -> System.out.println("First: " + i)); 46 | Thread.sleep(500); 47 | Subscription s2 = cold.subscribe(i -> System.out.println("Second: " + i)); 48 | Thread.sleep(500); 49 | System.out.println("Unsubscribe first"); 50 | s2.unsubscribe(); 51 | Thread.sleep(500); 52 | System.out.println("Unsubscribe first"); 53 | s1.unsubscribe(); 54 | 55 | System.out.println("First connection again"); 56 | Thread.sleep(500); 57 | s1 = cold.subscribe(i -> System.out.println("First: " + i)); 58 | 59 | // First: 0 60 | // First: 1 61 | // First: 2 62 | // Second: 2 63 | // First: 3 64 | // Second: 3 65 | // Unsubscribe first 66 | // First: 4 67 | // First: 5 68 | // First: 6 69 | // Unsubscribe first 70 | // First connection again 71 | // First: 0 72 | // First: 1 73 | // First: 2 74 | // First: 3 75 | // First: 4 76 | } 77 | 78 | 79 | // 80 | // Test 81 | // 82 | 83 | @Test 84 | public void testRefcount() throws InterruptedException { 85 | TestScheduler scheduler = Schedulers.test(); 86 | TestSubscriber tester1 = new TestSubscriber(); 87 | TestSubscriber tester2 = new TestSubscriber(); 88 | TestSubscriber tester3 = new TestSubscriber(); 89 | 90 | Observable cold = 91 | Observable 92 | .interval(200, TimeUnit.MILLISECONDS, scheduler) 93 | .share(); 94 | 95 | Subscription s1 = cold.subscribe(tester1); 96 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 97 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L)); 98 | tester2.assertReceivedOnNext(Arrays.asList()); 99 | tester3.assertReceivedOnNext(Arrays.asList()); 100 | 101 | Subscription s2 = cold.subscribe(tester2); 102 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 103 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L)); 104 | tester2.assertReceivedOnNext(Arrays.asList(2L, 3L, 4L)); 105 | tester3.assertReceivedOnNext(Arrays.asList()); 106 | 107 | s2.unsubscribe(); 108 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 109 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L, 5L, 6L)); 110 | tester2.assertReceivedOnNext(Arrays.asList(2L, 3L, 4L)); 111 | tester3.assertReceivedOnNext(Arrays.asList()); 112 | 113 | s1.unsubscribe(); 114 | Subscription s3 = cold.subscribe(tester3); 115 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 116 | tester1.assertReceivedOnNext(Arrays.asList(0L, 1L, 2L, 3L, 4L, 5L, 6L)); 117 | tester2.assertReceivedOnNext(Arrays.asList(2L, 3L, 4L)); 118 | tester3.assertReceivedOnNext(Arrays.asList(0L, 1L)); 119 | 120 | s3.unsubscribe(); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/leaving/FirstLastSingleExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.leaving; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | import org.junit.Test; 33 | 34 | import rx.Observable; 35 | 36 | public class FirstLastSingleExample { 37 | 38 | public void exampleFirst() { 39 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 40 | 41 | long value = values 42 | .take(5) 43 | .toBlocking() 44 | .first(i -> i>2); 45 | System.out.println(value); 46 | 47 | // 3 48 | } 49 | 50 | public void exampleSingleError() { 51 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 52 | 53 | try { 54 | long value = values 55 | .take(5) 56 | .toBlocking() 57 | .single(i -> i>2); 58 | System.out.println(value); 59 | } 60 | catch (Exception e) { 61 | System.out.println("Caught: " + e); 62 | } 63 | 64 | // Caught: java.lang.IllegalArgumentException: Sequence contains too many elements 65 | } 66 | 67 | 68 | // 69 | // Tests 70 | // 71 | 72 | @Test 73 | public void testFirst() throws InterruptedException { 74 | List received = new ArrayList<>(); 75 | 76 | Observable values = Observable.range(0,5); 77 | 78 | int value = values 79 | .take(5) 80 | .toBlocking() 81 | .first(i -> i>2); 82 | received.add(value); 83 | 84 | assertEquals(received, Arrays.asList(3)); 85 | } 86 | 87 | @Test(expected = IllegalArgumentException.class) 88 | public void testSingleError() { 89 | Observable values = Observable.range(0, 5); 90 | 91 | long value = values 92 | .take(5) 93 | .toBlocking() 94 | .single(i -> i>2); 95 | System.out.println(value); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/leaving/ForEachExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.leaving; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.lang.Thread.State; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.concurrent.TimeUnit; 32 | 33 | import org.junit.Test; 34 | 35 | import rx.Observable; 36 | import rx.schedulers.Schedulers; 37 | import rx.schedulers.TestScheduler; 38 | 39 | public class ForEachExample { 40 | 41 | public void exampleObservableForEach() { 42 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 43 | 44 | values 45 | .take(5) 46 | .forEach( 47 | v -> System.out.println(v)); 48 | System.out.println("Subscribed"); 49 | 50 | // Subscribed 51 | // 0 52 | // 1 53 | // 2 54 | // 3 55 | // 4 56 | } 57 | 58 | public void exampleBlockingForEach() { 59 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS); 60 | 61 | values 62 | .take(5) 63 | .toBlocking() 64 | .forEach( 65 | v -> System.out.println(v)); 66 | System.out.println("Subscribed"); 67 | 68 | // 0 69 | // 1 70 | // 2 71 | // 3 72 | // 4 73 | // Subscribed 74 | } 75 | 76 | public void exampleBlockingForEachError() { 77 | Observable values = Observable.error(new Exception("Oops")); 78 | 79 | try { 80 | values 81 | .take(5) 82 | .toBlocking() 83 | .forEach( 84 | v -> System.out.println(v)); 85 | } 86 | catch (Exception e) { 87 | System.out.println("Caught: " + e.getMessage()); 88 | } 89 | System.out.println("Subscribed"); 90 | 91 | // Caught: java.lang.Exception: Oops 92 | // Subscribed 93 | } 94 | 95 | 96 | // 97 | // Tests 98 | // 99 | 100 | @Test 101 | public void testObservableForEach() { 102 | List received = new ArrayList<>(); 103 | TestScheduler scheduler = Schedulers.test(); 104 | 105 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 106 | 107 | values 108 | .take(5) 109 | .forEach( 110 | i -> received.add(i)); 111 | received.add(-1L); // Mark that forEach statement returned 112 | 113 | assertEquals(received, Arrays.asList(-1L)); 114 | scheduler.advanceTimeBy(1, TimeUnit.SECONDS); 115 | assertEquals(received, Arrays.asList(-1L, 0L, 1L, 2L, 3L, 4L)); 116 | } 117 | 118 | @Test 119 | public void testBlockingForEach() throws InterruptedException { 120 | List received = new ArrayList<>(); 121 | TestScheduler scheduler = Schedulers.test(); 122 | 123 | Observable values = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); 124 | 125 | // Blocking call on new thread 126 | Thread thread = new Thread(() -> { 127 | values 128 | .take(5) 129 | .toBlocking() 130 | .forEach( 131 | i -> received.add(i)); 132 | received.add(-1L); // Mark that forEach statement returned 133 | 134 | }); 135 | thread.start(); 136 | 137 | assertEquals(received, Arrays.asList()); 138 | // Wait for blocking call to block before producing values 139 | while (thread.getState() != State.WAITING) 140 | Thread.sleep(1); 141 | scheduler.advanceTimeBy(1, TimeUnit.SECONDS); 142 | // Wait for processing to complete 143 | thread.join(50); 144 | assertEquals(received, Arrays.asList(0L, 1L, 2L, 3L, 4L, -1L)); 145 | } 146 | 147 | @Test(expected = Exception.class) 148 | public void testBlockingForEachError() { 149 | Observable values = Observable.error(new Exception("Oops")); 150 | 151 | values 152 | .take(5) 153 | .toBlocking() 154 | .forEach( 155 | v -> {}); 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/leaving/FutureExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.leaving; 24 | 25 | 26 | import static org.junit.Assert.*; 27 | 28 | import java.util.concurrent.ExecutionException; 29 | import java.util.concurrent.Future; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | import org.junit.Test; 33 | 34 | import rx.Observable; 35 | 36 | public class FutureExample { 37 | 38 | public void exampleFuture() { 39 | Observable values = Observable.timer(500, TimeUnit.MILLISECONDS); 40 | 41 | values.subscribe(v -> System.out.println("Emitted: " + v)); 42 | 43 | Future future = values.toBlocking().toFuture(); 44 | try { 45 | System.out.println(future.get()); 46 | } catch (InterruptedException e) { 47 | e.printStackTrace(); 48 | } catch (ExecutionException e) { 49 | e.printStackTrace(); 50 | } 51 | 52 | // Emitted: 0 53 | // 0 54 | } 55 | 56 | 57 | // 58 | // 59 | 60 | @Test 61 | public void testFuture() throws InterruptedException, ExecutionException { 62 | Observable sequence = Observable.just(0); 63 | Future future = sequence.toBlocking().toFuture(); 64 | int value = future.get(); 65 | assertEquals(0, value); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/sideeffects/MutablePipelineExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.sideeffects; 24 | 25 | import java.util.Arrays; 26 | 27 | import org.junit.Test; 28 | 29 | import rx.Observable; 30 | import rx.observers.TestSubscriber; 31 | 32 | public class MutablePipelineExample { 33 | 34 | private static class Data { 35 | public int id; 36 | public String name; 37 | public Data(int id, String name) { 38 | this.id = id; 39 | this.name = name; 40 | } 41 | } 42 | 43 | public void example() { 44 | Observable data = Observable.just( 45 | new Data(1, "Microsoft"), 46 | new Data(2, "Netflix") 47 | ); 48 | 49 | data.subscribe(d -> d.name = "Garbage"); 50 | data.subscribe(d -> System.out.println(d.id + ": " + d.name)); 51 | 52 | // 1: Garbage 53 | // 2: Garbage 54 | } 55 | 56 | 57 | // 58 | // Test 59 | // 60 | 61 | @Test 62 | public void test() { 63 | TestSubscriber tester = new TestSubscriber<>(); 64 | 65 | Observable data = Observable.just( 66 | new Data(1, "Microsoft"), 67 | new Data(2, "Netflix") 68 | ); 69 | 70 | data.subscribe(d -> d.name = "Garbage"); 71 | data.map(d -> d.name) 72 | .subscribe(tester); 73 | 74 | tester.assertReceivedOnNext(Arrays.asList("Garbage", "Garbage")); 75 | tester.assertTerminalEvent(); 76 | tester.assertNoErrors(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/timeshifted/SampleExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.timeshifted; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class SampleExample { 36 | 37 | public void exampleSample() { 38 | Observable.interval(150, TimeUnit.MILLISECONDS) 39 | .sample(1, TimeUnit.SECONDS) 40 | .take(3) 41 | .subscribe(System.out::println); 42 | 43 | // 5 44 | // 12 45 | // 18 46 | } 47 | 48 | 49 | // 50 | // Test 51 | // 52 | 53 | @Test 54 | public void testSample() { 55 | TestScheduler scheduler = Schedulers.test(); 56 | TestSubscriber tester = new TestSubscriber<>(); 57 | 58 | Observable.interval(150, TimeUnit.MILLISECONDS, scheduler) 59 | .sample(1, TimeUnit.SECONDS, scheduler) 60 | .take(3) 61 | .subscribe(tester); 62 | 63 | scheduler.advanceTimeBy(3, TimeUnit.SECONDS); 64 | tester.assertReceivedOnNext(Arrays.asList(5L, 12L, 18L)); 65 | tester.assertTerminalEvent(); 66 | tester.assertNoErrors(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/timeshifted/TakeLastBufferExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.timeshifted; 24 | 25 | import java.util.Arrays; 26 | import java.util.List; 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class TakeLastBufferExample { 37 | 38 | public void exampleByCount() { 39 | Observable.range(0, 5) 40 | .takeLastBuffer(2) 41 | .subscribe(System.out::println); 42 | 43 | // [3, 4] 44 | } 45 | 46 | public void exampleByTime() { 47 | Observable.interval(100, TimeUnit.MILLISECONDS) 48 | .take(5) 49 | .takeLastBuffer(200, TimeUnit.MILLISECONDS) 50 | .subscribe(System.out::println); 51 | 52 | // [2, 3, 4] 53 | } 54 | 55 | public void exampleByCountAndTime() { 56 | Observable.interval(100, TimeUnit.MILLISECONDS) 57 | .take(5) 58 | .takeLastBuffer(2, 200, TimeUnit.MILLISECONDS) 59 | .subscribe(System.out::println); 60 | 61 | // [3, 4] 62 | } 63 | 64 | 65 | // 66 | // Tests 67 | // 68 | 69 | @Test 70 | public void testByCount() { 71 | TestSubscriber> tester = new TestSubscriber<>(); 72 | 73 | Observable.range(0, 5) 74 | .takeLastBuffer(2) 75 | .subscribe(tester); 76 | 77 | tester.assertReceivedOnNext(Arrays.asList( 78 | Arrays.asList(3, 4) 79 | )); 80 | tester.assertTerminalEvent(); 81 | tester.assertNoErrors(); 82 | } 83 | 84 | @Test 85 | public void testByTime() { 86 | TestSubscriber> tester = new TestSubscriber<>(); 87 | TestScheduler scheduler = Schedulers.test(); 88 | 89 | Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 90 | .take(5) 91 | .takeLastBuffer(200, TimeUnit.MILLISECONDS, scheduler) 92 | .subscribe(tester); 93 | 94 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 95 | tester.assertReceivedOnNext(Arrays.asList( 96 | Arrays.asList(2L, 3L, 4L) 97 | )); 98 | tester.assertTerminalEvent(); 99 | tester.assertNoErrors(); 100 | } 101 | 102 | @Test 103 | public void testByCountAndTime() { 104 | TestSubscriber> tester = new TestSubscriber<>(); 105 | TestScheduler scheduler = Schedulers.test(); 106 | 107 | Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 108 | .take(5) 109 | .takeLastBuffer(2, 200, TimeUnit.MILLISECONDS, scheduler) 110 | .subscribe(tester); 111 | 112 | scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); 113 | tester.assertReceivedOnNext(Arrays.asList( 114 | Arrays.asList(3L, 4L) 115 | )); 116 | tester.assertTerminalEvent(); 117 | tester.assertNoErrors(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter3/timeshifted/ThrottleExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter3.timeshifted; 24 | 25 | import java.util.Arrays; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.observers.TestSubscriber; 32 | import rx.schedulers.Schedulers; 33 | import rx.schedulers.TestScheduler; 34 | 35 | public class ThrottleExample { 36 | 37 | public void exampleThrottleFirst() { 38 | Observable.interval(150, TimeUnit.MILLISECONDS) 39 | .throttleFirst(1, TimeUnit.SECONDS) 40 | .take(3) 41 | .subscribe(System.out::println); 42 | 43 | // 0 44 | // 7 45 | // 14 46 | } 47 | 48 | public void exampleThrottleLast() { 49 | Observable.interval(150, TimeUnit.MILLISECONDS) 50 | .throttleLast(1, TimeUnit.SECONDS) 51 | .take(3) 52 | .subscribe(System.out::println); 53 | 54 | // 5 55 | // 12 56 | // 18 57 | } 58 | 59 | 60 | // 61 | // Test 62 | // 63 | 64 | @Test 65 | public void testThrottleFirst() { 66 | TestScheduler scheduler = Schedulers.test(); 67 | TestSubscriber tester = new TestSubscriber<>(); 68 | 69 | Observable.interval(150, TimeUnit.MILLISECONDS, scheduler) 70 | .throttleFirst(1, TimeUnit.SECONDS, scheduler) 71 | .take(3) 72 | .subscribe(tester); 73 | 74 | scheduler.advanceTimeBy(3, TimeUnit.SECONDS); 75 | tester.assertReceivedOnNext(Arrays.asList(0L, 7L, 14L)); 76 | } 77 | 78 | @Test 79 | public void testThrottleLast() { 80 | TestScheduler scheduler = Schedulers.test(); 81 | TestSubscriber tester = new TestSubscriber<>(); 82 | 83 | Observable.interval(150, TimeUnit.MILLISECONDS, scheduler) 84 | .throttleLast(1, TimeUnit.SECONDS, scheduler) 85 | .take(3) 86 | .subscribe(tester); 87 | 88 | scheduler.advanceTimeBy(3, TimeUnit.SECONDS); 89 | tester.assertReceivedOnNext(Arrays.asList(5L, 12L, 18L)); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/backpressure/ConsumerSideExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.backpressure; 24 | 25 | import java.util.Arrays; 26 | import java.util.List; 27 | import java.util.concurrent.TimeUnit; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.observers.TestSubscriber; 33 | import rx.schedulers.Schedulers; 34 | import rx.schedulers.TestScheduler; 35 | 36 | public class ConsumerSideExample { 37 | 38 | public void exampleSample() { 39 | Observable.interval(1, TimeUnit.MILLISECONDS) 40 | .observeOn(Schedulers.newThread()) 41 | .sample(100, TimeUnit.MILLISECONDS) 42 | .take(3) 43 | .subscribe( 44 | i -> { 45 | System.out.println(i); 46 | try { 47 | Thread.sleep(100); 48 | } catch (Exception e) { } 49 | }, 50 | System.out::println); 51 | 52 | // 82 53 | // 182 54 | // 283 55 | } 56 | 57 | public void exampleBuffer() { 58 | Observable.interval(10, TimeUnit.MILLISECONDS) 59 | .observeOn(Schedulers.newThread()) 60 | .buffer(100, TimeUnit.MILLISECONDS) 61 | .take(3) 62 | .subscribe( 63 | i -> { 64 | System.out.println(i); 65 | try { 66 | Thread.sleep(100); 67 | } catch (Exception e) { } 68 | }, 69 | System.out::println); 70 | 71 | // [0, 1, 2, 3, 4, 5, 6, 7] 72 | // [8, 9, 10, 11, 12, 13, 14, 15, 16, 17] 73 | // [18, 19, 20, 21, 22, 23, 24, 25, 26, 27] 74 | } 75 | 76 | 77 | // 78 | // Test 79 | // 80 | 81 | @Test 82 | public void testSample() { 83 | TestScheduler scheduler = Schedulers.test(); 84 | TestSubscriber tester = new TestSubscriber() { 85 | @Override 86 | public void onNext(Long t) { 87 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 88 | super.onNext(t); 89 | } 90 | }; 91 | 92 | Observable.interval(1, TimeUnit.MILLISECONDS, scheduler) 93 | .observeOn(scheduler) 94 | .sample(100, TimeUnit.MILLISECONDS, scheduler) 95 | .take(3) 96 | .subscribe(tester); 97 | 98 | scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS); 99 | tester.assertReceivedOnNext(Arrays.asList(98L, 199L, 299L)); 100 | tester.assertNoErrors(); 101 | } 102 | 103 | @Test 104 | public void testBuffer() { 105 | TestScheduler scheduler = Schedulers.test(); 106 | TestSubscriber> tester = new TestSubscriber>() { 107 | @Override 108 | public void onNext(List t) { 109 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 110 | super.onNext(t); 111 | } 112 | }; 113 | 114 | Observable.interval(10, TimeUnit.MILLISECONDS, scheduler) 115 | .observeOn(scheduler) 116 | .buffer(100, TimeUnit.MILLISECONDS, scheduler) 117 | .take(3) 118 | .subscribe(tester); 119 | 120 | scheduler.advanceTimeBy(300, TimeUnit.MILLISECONDS); 121 | tester.assertReceivedOnNext(Arrays.asList( 122 | Arrays.asList( 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), 123 | Arrays.asList( 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L), 124 | Arrays.asList(20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L) 125 | )); 126 | tester.assertNoErrors(); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/backpressure/ControlledPullSubscriber.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.backpressure; 24 | 25 | import rx.Subscriber; 26 | import rx.functions.Action0; 27 | import rx.functions.Action1; 28 | 29 | /** 30 | * An Rx Subscriber that does not accept any items unless manually requested to. 31 | * 32 | * @author Chris 33 | * 34 | * @param 35 | */ 36 | public class ControlledPullSubscriber extends Subscriber { 37 | 38 | private final Action1 onNextAction; 39 | private final Action1 onErrorAction; 40 | private final Action0 onCompletedAction; 41 | 42 | public ControlledPullSubscriber( 43 | Action1 onNextAction, 44 | Action1 onErrorAction, 45 | Action0 onCompletedAction) { 46 | this.onNextAction = onNextAction; 47 | this.onErrorAction = onErrorAction; 48 | this.onCompletedAction = onCompletedAction; 49 | } 50 | 51 | public ControlledPullSubscriber( 52 | Action1 onNextAction, 53 | Action1 onErrorAction) { 54 | this(onNextAction, onErrorAction, () -> {}); 55 | } 56 | 57 | public ControlledPullSubscriber(Action1 onNextAction) { 58 | this(onNextAction, e -> {}, () -> {}); 59 | } 60 | 61 | @Override 62 | public void onStart() { 63 | request(0); 64 | } 65 | 66 | @Override 67 | public void onCompleted() { 68 | onCompletedAction.call(); 69 | } 70 | 71 | @Override 72 | public void onError(Throwable e) { 73 | onErrorAction.call(e); 74 | } 75 | 76 | @Override 77 | public void onNext(T t) { 78 | onNextAction.call(t); 79 | } 80 | 81 | public void requestMore(int n) { 82 | request(n); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/backpressure/NoBackpressureExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.backpressure; 24 | 25 | import static org.hamcrest.CoreMatchers.instanceOf; 26 | import static org.junit.Assert.*; 27 | 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.concurrent.TimeUnit; 32 | 33 | import org.junit.Test; 34 | 35 | import rx.Observable; 36 | import rx.observers.TestSubscriber; 37 | import rx.schedulers.Schedulers; 38 | import rx.schedulers.TestScheduler; 39 | 40 | public class NoBackpressureExample { 41 | 42 | public void exampleSynchronous() { 43 | // Produce 44 | Observable producer = Observable.create(o -> { 45 | o.onNext(1); 46 | o.onNext(2); 47 | o.onCompleted(); 48 | }); 49 | // Consume 50 | producer.subscribe(i -> { 51 | try { 52 | Thread.sleep(1000); 53 | System.out.println(i); 54 | } catch (Exception e) { } 55 | }); 56 | 57 | // 1 58 | // 2 59 | } 60 | 61 | public void exampleNoBackpressure() { 62 | Observable.interval(1, TimeUnit.MILLISECONDS) 63 | .observeOn(Schedulers.newThread()) 64 | .subscribe( 65 | i -> { 66 | System.out.println(i); 67 | try { 68 | Thread.sleep(100); 69 | } catch (Exception e) { } 70 | }, 71 | System.out::println); 72 | 73 | // 0 74 | // 1 75 | // rx.exceptions.MissingBackpressureException 76 | } 77 | 78 | 79 | // 80 | // Tests 81 | // 82 | 83 | @Test 84 | public void testSynchronous() { 85 | List execution = new ArrayList(); 86 | 87 | // Produce 88 | Observable producer = Observable.create(o -> { 89 | execution.add("Producing 1"); 90 | o.onNext(1); 91 | execution.add("Producing 2"); 92 | o.onNext(2); 93 | o.onCompleted(); 94 | }); 95 | // Consume 96 | producer.subscribe(i -> execution.add("Processed " + i)); 97 | 98 | assertEquals( 99 | Arrays.asList( 100 | "Producing 1", 101 | "Processed 1", 102 | "Producing 2", 103 | "Processed 2" 104 | ), 105 | execution); 106 | } 107 | 108 | @Test 109 | public void testNoBackpressure() { 110 | TestScheduler scheduler = Schedulers.test(); 111 | TestSubscriber tester = new TestSubscriber() { 112 | @Override 113 | public void onNext(Long t) { 114 | scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); 115 | super.onNext(t); 116 | } 117 | }; 118 | 119 | Observable.interval(1, TimeUnit.MILLISECONDS, scheduler) 120 | .observeOn(scheduler) 121 | .subscribe(tester); 122 | 123 | scheduler.advanceTimeBy(10, TimeUnit.MILLISECONDS); 124 | assertThat( 125 | tester.getOnErrorEvents().get(0), 126 | instanceOf(rx.exceptions.MissingBackpressureException.class)); 127 | 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/backpressure/OnRequestExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.backpressure; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | import static org.junit.Assert.assertTrue; 27 | 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | 32 | import org.junit.Test; 33 | 34 | import rx.Observable; 35 | 36 | public class OnRequestExample { 37 | 38 | public void exampleOnRequest() { 39 | Observable.range(0, 3) 40 | .doOnRequest(i -> System.out.println("Requested " + i)) 41 | .subscribe(System.out::println); 42 | 43 | // Requested 9223372036854775807 44 | // 0 45 | // 1 46 | // 2 47 | } 48 | 49 | public void exampleOnRequestZip() { 50 | Observable.range(0, 300) 51 | .doOnRequest(i -> System.out.println("Requested " + i)) 52 | .zipWith( 53 | Observable.range(10, 300), 54 | (i1, i2) -> i1 + " - " + i2) 55 | .take(300) 56 | .subscribe(); 57 | 58 | // Requested 128 59 | // Requested 90 60 | // Requested 90 61 | // Requested 90 62 | 63 | } 64 | 65 | public void exampleOnRequestManual() { 66 | ControlledPullSubscriber puller = 67 | new ControlledPullSubscriber(System.out::println); 68 | 69 | Observable.range(0, 3) 70 | .doOnRequest(i -> System.out.println("Requested " + i)) 71 | .subscribe(puller); 72 | 73 | puller.requestMore(2); 74 | puller.requestMore(1); 75 | 76 | // Requested 0 77 | // Requested 2 78 | // 0 79 | // 1 80 | // Requested 1 81 | // 2 82 | } 83 | 84 | 85 | // 86 | // Tests 87 | // 88 | 89 | @Test 90 | public void testOnRequest() { 91 | List requests = new ArrayList(); 92 | 93 | Observable.range(0, 3) 94 | .doOnRequest(requests::add) 95 | .subscribe(); 96 | 97 | assertEquals(Arrays.asList(Long.MAX_VALUE), requests); 98 | } 99 | 100 | @Test 101 | public void testOnRequestZip() { 102 | List requests = new ArrayList(); 103 | 104 | Observable.range(0, 300) 105 | .doOnRequest(requests::add) 106 | .zipWith( 107 | Observable.range(10, 300), 108 | (i1, i2) -> i1 + " - " + i2) 109 | .take(300) 110 | .subscribe(); 111 | 112 | assertTrue("zip makes subsequent requests", 113 | requests.size() > 1); 114 | assertEquals("zip uses a buffer of 128", 115 | requests.get(0), new Long(128)); 116 | } 117 | 118 | @Test 119 | public void testOnRequestManual() { 120 | List received = new ArrayList(); 121 | List requests = new ArrayList(); 122 | 123 | ControlledPullSubscriber puller = 124 | new ControlledPullSubscriber(received::add); 125 | 126 | Observable.range(0, 3) 127 | .doOnRequest(requests::add) 128 | .subscribe(puller); 129 | 130 | assertEquals(Arrays.asList(0L), requests); 131 | assertEquals(Arrays.asList(), received); 132 | puller.requestMore(2); 133 | assertEquals(Arrays.asList(0L, 2L), requests); 134 | assertEquals(Arrays.asList(0, 1), received); 135 | puller.requestMore(1); 136 | assertEquals(Arrays.asList(0L, 2L, 1L), requests); 137 | assertEquals(Arrays.asList(0, 1, 2), received); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/backpressure/ReactivePullExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.backpressure; 24 | 25 | import static org.junit.Assert.assertEquals; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | 31 | import org.junit.Test; 32 | 33 | import rx.Observable; 34 | 35 | public class ReactivePullExample { 36 | 37 | public void example() { 38 | ControlledPullSubscriber tester = new ControlledPullSubscriber( 39 | i -> System.out.println("Consumed " + i)); 40 | 41 | Observable.range(0, 100) 42 | .subscribe(tester); 43 | 44 | System.out.println("Requesting 2 more"); 45 | tester.requestMore(2); 46 | System.out.println("Requesting 3 more"); 47 | tester.requestMore(3); 48 | 49 | // Requesting 2 more 50 | // Consumed 0 51 | // Consumed 1 52 | // Requesting 3 more 53 | // Consumed 2 54 | // Consumed 3 55 | // Consumed 4 56 | } 57 | 58 | 59 | // 60 | // Test 61 | // 62 | 63 | @Test 64 | public void test() { 65 | List received = new ArrayList<>(); 66 | ControlledPullSubscriber tester = new ControlledPullSubscriber(received::add); 67 | 68 | Observable.range(0, 100) 69 | .subscribe(tester); 70 | 71 | assertEquals(Arrays.asList(), received); 72 | tester.requestMore(2); 73 | assertEquals(Arrays.asList(0, 1), received); 74 | tester.requestMore(3); 75 | assertEquals(Arrays.asList(0, 1, 2, 3, 4), received); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/scheduling/ObserveOnExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.scheduling; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import org.junit.Assert; 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.schedulers.Schedulers; 32 | 33 | public class ObserveOnExample { 34 | 35 | public void exampleObserveOn() { 36 | Observable.create(o -> { 37 | System.out.println("Created on " + Thread.currentThread().getId()); 38 | o.onNext(1); 39 | o.onNext(2); 40 | o.onCompleted(); 41 | }) 42 | .observeOn(Schedulers.newThread()) 43 | .subscribe(i -> 44 | System.out.println("Received " + i + " on " + Thread.currentThread().getId())); 45 | 46 | // Created on 1 47 | // Received 1 on 13 48 | // Received 2 on 13 49 | } 50 | 51 | public void exampleObserveOnBeforeAfter() { 52 | Observable.create(o -> { 53 | System.out.println("Created on " + Thread.currentThread().getId()); 54 | o.onNext(1); 55 | o.onNext(2); 56 | o.onCompleted(); 57 | }) 58 | .doOnNext(i -> 59 | System.out.println("Before " + i + " on " + Thread.currentThread().getId())) 60 | .observeOn(Schedulers.newThread()) 61 | .doOnNext(i -> 62 | System.out.println("After " + i + " on " + Thread.currentThread().getId())) 63 | .subscribe(); 64 | 65 | // Created on 1 66 | // Before 1 on 1 67 | // Before 2 on 1 68 | // After 1 on 13 69 | // After 2 on 13 70 | } 71 | 72 | 73 | // 74 | // Test 75 | // 76 | 77 | @Test 78 | public void testObserveOn() { 79 | long[] threads = {0, 0}; 80 | 81 | Observable.create(o -> { 82 | threads[0] = Thread.currentThread().getId(); 83 | o.onNext(1); 84 | o.onNext(2); 85 | o.onCompleted(); 86 | }) 87 | .observeOn(Schedulers.newThread()) 88 | .subscribe(i -> threads[1] = Thread.currentThread().getId()); 89 | 90 | Assert.assertNotEquals("Create and receive on different threads", threads[0], threads[1]); 91 | } 92 | 93 | @Test 94 | public void testObserveOnBeforeAfter() { 95 | long[] threads = {0, 0, 0, 0, 0}; 96 | 97 | threads[0] = Thread.currentThread().getId(); 98 | 99 | Observable.create(o -> { 100 | threads[1] = Thread.currentThread().getId(); 101 | o.onNext(1); 102 | o.onNext(2); 103 | o.onCompleted(); 104 | }) 105 | .doOnNext(i -> threads[2] = Thread.currentThread().getId()) 106 | .observeOn(Schedulers.newThread()) 107 | .doOnNext(i -> threads[3] = Thread.currentThread().getId()) 108 | .subscribe(i -> threads[4] = Thread.currentThread().getId()); 109 | 110 | assertEquals("Create on main thread", threads[0], threads[1]); 111 | assertEquals("Synchronous before observeOn", threads[1], threads[2]); 112 | assertEquals("Synchronous after observeOn", threads[3], threads[4]); 113 | assertNotEquals("Before and after observeOn on different threads", threads[2], threads[3]); 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/scheduling/SingleThreadedExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.scheduling; 24 | 25 | import org.junit.Assert; 26 | import org.junit.Test; 27 | 28 | import rx.subjects.BehaviorSubject; 29 | 30 | public class SingleThreadedExample { 31 | 32 | public void example() { 33 | final BehaviorSubject subject = BehaviorSubject.create(); 34 | subject.subscribe(i -> { 35 | System.out.println("Received " + i + " on " + Thread.currentThread().getId()); 36 | }); 37 | 38 | int[] i = {1}; // naughty side-effects for examples only ;) 39 | Runnable r = () -> { 40 | synchronized(i) { 41 | System.out.println("onNext(" + i[0] + ") on " + Thread.currentThread().getId()); 42 | subject.onNext(i[0]++); 43 | } 44 | }; 45 | 46 | r.run(); // Execute on main thread 47 | new Thread(r).start(); 48 | new Thread(r).start(); 49 | 50 | // onNext(1) on 1 51 | // Received 1 on 1 52 | // onNext(2) on 11 53 | // Received 2 on 11 54 | // onNext(3) on 12 55 | // Received 3 on 12 56 | } 57 | 58 | 59 | // 60 | // Test 61 | // 62 | 63 | @Test 64 | public void test() throws InterruptedException { 65 | long[] emitted = {0, 0, 0}; 66 | long[] received = {0, 0, 0}; 67 | 68 | final BehaviorSubject subject = BehaviorSubject.create(); 69 | subject.subscribe(i -> { 70 | received[i] = Thread.currentThread().getId(); 71 | }); 72 | 73 | int[] i = {0}; // naughty side-effects for examples only ;) 74 | Runnable r = () -> { 75 | synchronized(i) { 76 | int value = i[0]; 77 | emitted[value] = Thread.currentThread().getId(); 78 | subject.onNext(i[0]++); 79 | } 80 | }; 81 | 82 | r.run(); // Execute on main thread 83 | Thread t1 = new Thread(r); 84 | Thread t2 = new Thread(r); 85 | t1.start(); 86 | t2.start(); 87 | t1.join(); 88 | t2.join(); 89 | 90 | Assert.assertArrayEquals("onNext and handler executed on the same thread", 91 | emitted, received); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/scheduling/UnsubscribeOnExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.scheduling; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | import java.util.Arrays; 28 | 29 | import org.junit.Test; 30 | 31 | import rx.Observable; 32 | import rx.schedulers.Schedulers; 33 | 34 | public class UnsubscribeOnExample { 35 | 36 | public static void example() { 37 | Observable source = Observable.using( 38 | () -> { 39 | System.out.println("Subscribed on " + Thread.currentThread().getId()); 40 | return Arrays.asList(1,2); 41 | }, 42 | (ints) -> { 43 | System.out.println("Producing on " + Thread.currentThread().getId()); 44 | return Observable.from(ints); 45 | }, 46 | (ints) -> { 47 | System.out.println("Unubscribed on " + Thread.currentThread().getId()); 48 | } 49 | ); 50 | 51 | source 52 | .unsubscribeOn(Schedulers.newThread()) 53 | .subscribe(System.out::println); 54 | 55 | // Subscribed on 1 56 | // Producing on 1 57 | // 1 58 | // 2 59 | // Unubscribed on 11 60 | } 61 | 62 | 63 | // 64 | // Test 65 | // 66 | 67 | @Test 68 | public void test() { 69 | long[] threads = {0, 0, 0}; 70 | 71 | Observable source = Observable.using( 72 | () -> { 73 | threads[0] = Thread.currentThread().getId(); 74 | return Arrays.asList(1,2); 75 | }, 76 | (ints) -> { 77 | threads[1] = Thread.currentThread().getId(); 78 | return Observable.from(ints); 79 | }, 80 | (ints) -> { 81 | threads[2] = Thread.currentThread().getId(); 82 | } 83 | ); 84 | 85 | source 86 | .unsubscribeOn(Schedulers.newThread()) 87 | .subscribe(); 88 | 89 | assertEquals(threads[0], threads[1]); 90 | assertNotEquals(threads[0], threads[2]); 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/testing/ExampleExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.testing; 24 | 25 | import static org.junit.Assert.assertTrue; 26 | 27 | import java.util.ArrayList; 28 | import java.util.Arrays; 29 | import java.util.List; 30 | import java.util.concurrent.TimeUnit; 31 | 32 | import org.junit.Test; 33 | 34 | import rx.Observable; 35 | import rx.schedulers.TestScheduler; 36 | 37 | public class ExampleExample { 38 | 39 | @Test 40 | public void test() { 41 | TestScheduler scheduler = new TestScheduler(); 42 | List expected = Arrays.asList(0L, 1L, 2L, 3L, 4L); 43 | List result = new ArrayList<>(); 44 | Observable 45 | .interval(1, TimeUnit.SECONDS, scheduler) 46 | .take(5) 47 | .subscribe(i -> result.add(i)); 48 | assertTrue(result.isEmpty()); 49 | scheduler.advanceTimeBy(5, TimeUnit.SECONDS); 50 | assertTrue(result.equals(expected)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /tests/java/itrx/chapter4/testing/TestSubscriberExample.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2015 Christos Froussios 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | * 22 | *******************************************************************************/ 23 | package itrx.chapter4.testing; 24 | 25 | import static org.junit.Assert.assertTrue; 26 | 27 | import java.util.Arrays; 28 | import java.util.List; 29 | import java.util.concurrent.TimeUnit; 30 | 31 | import org.junit.Test; 32 | 33 | import rx.Observable; 34 | import rx.observers.TestSubscriber; 35 | import rx.schedulers.TestScheduler; 36 | 37 | public class TestSubscriberExample { 38 | 39 | @Test 40 | public void test() { 41 | TestScheduler scheduler = new TestScheduler(); 42 | TestSubscriber subscriber = new TestSubscriber<>(); 43 | List expected = Arrays.asList(0L, 1L, 2L, 3L, 4L); 44 | Observable 45 | .interval(1, TimeUnit.SECONDS, scheduler) 46 | .take(5) 47 | .subscribe(subscriber); 48 | assertTrue(subscriber.getOnNextEvents().isEmpty()); 49 | scheduler.advanceTimeBy(5, TimeUnit.SECONDS); 50 | subscriber.assertReceivedOnNext(expected); 51 | subscriber.assertTerminalEvent(); 52 | subscriber.assertNoErrors(); 53 | subscriber.assertUnsubscribed(); 54 | } 55 | } 56 | --------------------------------------------------------------------------------