├── LICENSE ├── README.md ├── pom.xml └── src └── main └── scala └── com └── grahamlea └── examples └── rxjava └── threading ├── Example01_NoThreading.scala ├── Example02_SubscribeOnGenerator.scala ├── Example02x_SubscribeOnGeneratorButDontUseIt.scala ├── Example03_ObserveOnGenerator.scala ├── Example04_ObserveOnGeneratorAndMapper.scala ├── Example05_ObserveOnAfterSubscribeOn.scala ├── Example06_SubscribeOnAfterObserveOn.scala ├── Example06x_TwoSubscribeOnCalls.scala ├── Example07_ImplicitThreading.scala ├── Example08_Parallel.scala ├── Example08x_Parallel_NoWorkInsideParallel.scala ├── Example09_CombinedGeneratorsWithSubscribeOn.scala ├── Example10_CombinedGeneratorsWithTwoSubscribeOns.scala ├── Example11_UsingAsyncStart.scala ├── Example12_UsingAsyncFromCallable.scala └── package.scala /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | RxJava Threading Examples 2 | ========================= 3 | 4 | Full code examples in Scala for my blog: [RxJava Threading Examples](http://www.grahamlea.com/2014/07/rxjava-threading-examples/) 5 | 6 | There's comments in the code that explain most of what's going on, but I discuss things in more depth in the blog. 7 | 8 | Examples that have an 'x' after the number are bad examples, i.e. demonstrating things that you shouldn't do. 9 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.grahamlea.examples 5 | rxjava-threading-examples-scala 6 | 1.0-SNAPSHOT 7 | RxJava Threading Examples in Scala 8 | 2014 9 | 10 | 11 | Apache License 2.0 12 | http://www.apache.org/licenses/LICENSE-2.0.html 13 | manual 14 | 15 | 16 | 17 | 18 | UTF-8 19 | 2.10.4 20 | 0.19.0 21 | 1.6 22 | 1.6 23 | 24 | 25 | 26 | 27 | org.scala-lang 28 | scala-library 29 | ${scala.version} 30 | 31 | 32 | com.netflix.rxjava 33 | rxjava-scala 34 | ${rxjava.version} 35 | 36 | 37 | com.netflix.rxjava 38 | rxjava-async-util 39 | ${rxjava.version} 40 | 41 | 42 | joda-time 43 | joda-time 44 | 2.3 45 | 46 | 47 | 48 | 49 | src/main/scala 50 | src/test/scala 51 | 52 | 53 | org.scala-tools 54 | maven-scala-plugin 55 | 2.15.0 56 | 57 | 58 | 59 | compile 60 | testCompile 61 | 62 | 63 | 64 | -make:transitive 65 | -dependencyfile 66 | ${project.build.directory}/.scala_dependencies 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.apache.maven.plugins 74 | maven-surefire-plugin 75 | 2.6 76 | 77 | false 78 | true 79 | 80 | 81 | 82 | **/*Test.* 83 | **/*Suite.* 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example01_NoThreading.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | /** 5 | * All this code runs on the 'main' thread. 6 | * Though RxJava is all about "asynchronous sequences", by default 7 | * everything just happens on the thread that subscribes. 8 | */ 9 | object Example01_NoThreading extends App { 10 | val shiftedUp = generator.map(shiftUp).debug("Shifted Up") 11 | 12 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 13 | 14 | shiftedDown.subscribe(debug("Received", _)) 15 | } 16 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example02_SubscribeOnGenerator.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.IOScheduler 5 | 6 | /** 7 | * Shows how using subscribeOn(), at any point in the chain, makes 8 | * the source Observable run using the specified scheduler 9 | */ 10 | object Example02_SubscribeOnGenerator extends App { 11 | val shiftedUp = generator.subscribeOn(IOScheduler()).map(shiftUp).debug("Shifted Up") 12 | 13 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 14 | 15 | shiftedDown.subscribe(debug("Received", _)) 16 | 17 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 18 | Thread.sleep(1000) 19 | } 20 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example02x_SubscribeOnGeneratorButDontUseIt.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.IOScheduler 5 | 6 | /** 7 | * Shows how subscribeOn() doesn't change the Observable, but 8 | * creates a new Observable that will subscribe using the specified 9 | * Scheduler. 10 | * 11 | * See that the Observable returned by subscribeOn() is never used 12 | * here, and consequently everything runs on the main thread. 13 | */ 14 | object Example02x_SubscribeOnGeneratorButDontUseIt extends App { 15 | val aGenerator = generator 16 | 17 | val neverUsed = aGenerator.subscribeOn(IOScheduler()) 18 | 19 | val shiftedUp = aGenerator.map(shiftUp).debug("Shifted Up") 20 | 21 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 22 | 23 | shiftedDown.subscribe(debug("Received", _)) 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example03_ObserveOnGenerator.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.IOScheduler 5 | 6 | /** 7 | * Shows how observeOn() works, notably that the source Observable 8 | * still runs on the thread that calls subscribe(), but all code 9 | * from the observeOn() call onwards executes using the specified 10 | * Scheduler. 11 | * 12 | * On my machine, this example generates all values on the main 13 | * thread before all further processing of the values is performed 14 | * sequentially on thread "RxComputationThreadPool-1". So observeOn() 15 | * doesn't result in each value being processed in parallel, but just 16 | * on a single different thread. 17 | */ 18 | object Example03_ObserveOnGenerator extends App { 19 | 20 | val shiftedUp = generator.observeOn(IOScheduler()).map(shiftUp).debug("Shifted Up") 21 | 22 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 23 | 24 | shiftedDown.subscribe(debug("Received", _)) 25 | 26 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 27 | Thread.sleep(1000) 28 | } 29 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example04_ObserveOnGeneratorAndMapper.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.{IOScheduler, ComputationScheduler} 5 | 6 | /** 7 | * Shows how observeOn() can be used at multiple points through a 8 | * flow to change the threads being used for different parts of 9 | * processing. 10 | * 11 | * Interestingly, on my machine, values are still dealt with 12 | * sequentially after being generated by the main thread, even 13 | * though processing is happening on two different threads. This 14 | * continues to be true even if the delay in the second map() 15 | * operation is significantly increased. This suggests to me that 16 | * the work in the first scheduler blocks waiting on the work in 17 | * the downstream scheduler before continuing. 18 | */ 19 | object Example04_ObserveOnGeneratorAndMapper extends App { 20 | 21 | val shiftedUp = generator.observeOn(IOScheduler()).map(shiftUp).debug("Shifted Up") 22 | 23 | val shiftedDown = shiftedUp.observeOn(ComputationScheduler()).map(shiftDown).debug("Shifted Down") 24 | 25 | shiftedDown.subscribe(debug("Received", _)) 26 | 27 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 28 | Thread.sleep(1000) 29 | } 30 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example05_ObserveOnAfterSubscribeOn.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.{IOScheduler, ComputationScheduler} 5 | 6 | /** 7 | * Demonstrates subscribeOn() and observeOn() being used together, 8 | * showing how the subscribeOn() Scheduler is used for all operations 9 | * from the source Observable to the point where observeOn is called. 10 | * 11 | * On my machine, this combination results in operations on different 12 | * values being processed in parallel. This suggests that, contrary to 13 | * the double observeOn() example, a thread scheduled with 14 | * subscribeOn() does not block waiting on the work in the downstream 15 | * scheduler before generating and processing the next value. 16 | */ 17 | object Example05_ObserveOnAfterSubscribeOn extends App { 18 | 19 | val shiftedUp = generator.subscribeOn(ComputationScheduler()).map(shiftUp).debug("Shifted Up") 20 | 21 | val shiftedDown = shiftedUp.observeOn(IOScheduler()).map(shiftDown).debug("Shifted Down") 22 | 23 | shiftedDown.subscribe(debug("Received", _)) 24 | 25 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 26 | Thread.sleep(1000) 27 | } 28 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example06_SubscribeOnAfterObserveOn.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.{IOScheduler, ComputationScheduler} 5 | 6 | /** 7 | * Demonstrates subscribeOn() and observeOn() being used together, 8 | * but this time with subscribeOn() being specified later in the flow 9 | * than observeOn(). 10 | * 11 | * This example operates exactly the same as the previous one where 12 | * subscribeOn() appeared earlier in the flow. This shows that in a 13 | * non-forked flow, the position of a subscribeOn() call has no 14 | * effect - it always dictates the thread used to subscribe to the 15 | * source Observable. 16 | */ 17 | object Example06_SubscribeOnAfterObserveOn extends App { 18 | 19 | val shiftedUp = generator.map(shiftUp).debug("Shifted Up") 20 | 21 | val shiftedDown = shiftedUp.observeOn(IOScheduler()).map(shiftDown).debug("Shifted Down") 22 | 23 | shiftedDown.subscribeOn(ComputationScheduler()).subscribe(debug("Received", _)) 24 | 25 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 26 | Thread.sleep(1000) 27 | } 28 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example06x_TwoSubscribeOnCalls.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.{IOScheduler, ComputationScheduler} 5 | 6 | /** 7 | * This BAD example shows that, if you erroneously apply two 8 | * subscribeOn() calls in one flow, the earliest application 9 | * takes precedence and later subscribeOn()s are effectively 10 | * ignored. 11 | */ 12 | object Example06x_TwoSubscribeOnCalls extends App { 13 | 14 | val shiftedUp = generator.subscribeOn(ComputationScheduler()).map(shiftUp).debug("Shifted Up") 15 | 16 | val shiftedDown = shiftedUp.subscribeOn(IOScheduler()).map(shiftDown).debug("Shifted Down") 17 | 18 | shiftedDown.subscribe(debug("Received", _)) 19 | 20 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 21 | Thread.sleep(1000) 22 | } 23 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example07_ImplicitThreading.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import scala.concurrent.duration.{Duration, MILLISECONDS} 5 | 6 | /** 7 | * Shows that you don't necessarily have to call subscribeOn() 8 | * or observeOn() for operations to start occurring on different 9 | * threads. Some built-in operations, such as delay() here, 10 | * internally use threading to achieve their behaviour. 11 | */ 12 | object Example07_ImplicitThreading extends App { 13 | 14 | val shiftedUp = generator.map(shiftUp).debug("Shifted Up") 15 | 16 | val delayed = shiftedUp.delay(Duration(10, MILLISECONDS)).debug("Delayed") 17 | 18 | val shiftedDown = delayed.map(shiftDown).debug("Shifted Down") 19 | 20 | shiftedDown.subscribe(debug("Received", _)) 21 | 22 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 23 | Thread.sleep(1000) 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example08_Parallel.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.Observable 5 | 6 | /** 7 | * Shows the use of parallel() to process multiple values concurrently. 8 | * 9 | * Assuming you have more than 1 core, the output should show that operations 10 | * on a value are interleaved with operations on other values. 11 | * 12 | * Interestingly, I see that the subscriber may be called by any of the 13 | * threads in the thread pool, but not necessarily by the one that performed 14 | * the processing of that value. 15 | */ 16 | object Example08_Parallel extends App { 17 | 18 | val shiftedUpAndDownInParallel = 19 | generator.parallel((f: Observable[Int]) => { 20 | val shiftedUp = f.map(shiftUp).debug("Shifted Up") 21 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 22 | shiftedDown 23 | }) 24 | 25 | shiftedUpAndDownInParallel.subscribe(debug("Received", _)) 26 | 27 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 28 | Thread.sleep(1000) 29 | } 30 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example08x_Parallel_NoWorkInsideParallel.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | /** 5 | * Shows that simply calling parallel() somewhere in the chain doesn't 6 | * necessarily result that downstream operations occurring in parallel, 7 | * or even on different threads. 8 | */ 9 | object Example08x_Parallel_NoWorkInsideParallel extends App { 10 | 11 | val shiftedUp = generator.parallel(f => f).map(shiftUp).debug("Shifted Up") 12 | 13 | val shiftedDown = shiftedUp.map(shiftDown).debug("Shifted Down") 14 | 15 | shiftedDown.subscribe(debug("Received", _)) 16 | 17 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 18 | Thread.sleep(1000) 19 | } 20 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example09_CombinedGeneratorsWithSubscribeOn.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.IOScheduler 5 | 6 | /** 7 | * Shows how using subscribeOn() in a flow where two generators are 8 | * combined doesn't result in parallel execution of the generators 9 | * if the subscribeOn() call is after the flows are combined 10 | * (using zip, in this case). 11 | */ 12 | object Example09_CombinedGeneratorsWithSubscribeOn extends App { 13 | val generator1 = generator.map(shiftUp).debug("Shifted Up #1") 14 | val generator2 = generator.map(shiftUp).debug("Shifted Up #2") 15 | 16 | val zipped = generator1.zip(generator2).map(_._1).debug("Zipped") 17 | 18 | val shiftedDown = zipped.map(shiftDown).debug("Shifted Down") 19 | 20 | shiftedDown.subscribeOn(IOScheduler()).subscribe(debug("Received", _)) 21 | 22 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 23 | Thread.sleep(1000) 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example10_CombinedGeneratorsWithTwoSubscribeOns.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.schedulers.IOScheduler 5 | 6 | /** 7 | * Shows how using subscribeOn() in a flow where two generators are 8 | * combined can achieve parallel execution of the generators 9 | * if the subscribeOn() calls are before the flows are combined 10 | * (using zip, in this case). 11 | * 12 | * On small sets with fixed delays, the subscriber always receives 13 | * values on the same thread. However, randomising the delays and 14 | * generating a larger set will show that values are delivered from 15 | * any thread (probably determined by whichever thread delivers the 16 | * last value to the zip() Observable). 17 | */ 18 | object Example10_CombinedGeneratorsWithTwoSubscribeOns extends App { 19 | val generatorSubscribed = generator.subscribeOn(IOScheduler()) 20 | val shiftedUp1 = generatorSubscribed.map(shiftUp).debug("Shifted Up #1") 21 | val shiftedUp2 = generatorSubscribed.map(shiftUp).debug("Shifted Up #2") 22 | 23 | val zipped = shiftedUp1.zip(shiftedUp2).map(_._1).debug("Zipped") 24 | 25 | val shiftedDown = zipped.map(shiftDown).debug("Shifted Down") 26 | 27 | shiftedDown.subscribe(debug("Received", _)) 28 | 29 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 30 | Thread.sleep(1000) 31 | } 32 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example11_UsingAsyncStart.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.ImplicitFunctionConversions.scalaFunction0ToRxFunc0 5 | import rx.lang.scala.JavaConversions.toScalaObservable 6 | import rx.util.async.Async 7 | import rx.lang.scala.Observable 8 | 9 | /** 10 | * Shows using Async.start() to execute a function asynchronously 11 | * whose return value is then emitted by an Observable. 12 | * 13 | * I find this example doesn't do what I think it should. If the 14 | * function returns a value immediately, before the subscriber 15 | * subscribes, then the debug("Generated") is executed on the main 16 | * thread and the rest of the chain works as expected. 17 | * 18 | * However, if the function completes after the subscriber has 19 | * subscribed, the debug("Generated") is executed on the Async 20 | * thread, and I find that the value from the function is never 21 | * delivered to the rest of the chain. 22 | */ 23 | object Example11_UsingAsyncStart extends App { 24 | 25 | def sleepThenGenerate(n: Int)() = { 26 | // When this sleep is present, and the subscriber attaches 27 | // before the values are emitted, I see nothing delivered by 28 | // the Observables from Async. 29 | debug("Generating", n) 30 | Thread.sleep(800) 31 | debug("Sending", n) 32 | n 33 | } 34 | 35 | val asyncGenerator1: Observable[Int] = Async.start(sleepThenGenerate(1) _) 36 | val asyncGenerator2: Observable[Int] = Async.start(sleepThenGenerate(2) _) 37 | 38 | val shiftedUp1 = asyncGenerator1.debug("Generated").map(shiftUp).debug("Shifted Up #1") 39 | val shiftedUp2 = asyncGenerator2.debug("Generated").map(shiftUp).debug("Shifted Up #2") 40 | 41 | val zipped = shiftedUp1.zip(shiftedUp2).map(_._1).debug("Zipped") 42 | 43 | val shiftedDown = zipped.map(shiftDown).debug("Shifted Down") 44 | 45 | Thread.sleep(100) 46 | println("Subscribing...") 47 | shiftedDown.subscribe( 48 | onNext = debug("Received", _), 49 | onCompleted = () => {println("Completed")}, 50 | onError = (t) => {} 51 | ) 52 | 53 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 54 | Thread.sleep(2000) 55 | } 56 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/Example12_UsingAsyncFromCallable.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava.threading 3 | 4 | import rx.lang.scala.ImplicitFunctionConversions.scalaFunction0ToRxFunc0 5 | import rx.lang.scala.JavaConversions.toScalaObservable 6 | import rx.util.async.Async 7 | import rx.lang.scala.Observable 8 | 9 | /** 10 | * Shows using Async.fromCallable() to execute a function 11 | * asynchronously whose return value then emitted by an Observable. 12 | * 13 | * Unlike Async.start(), this example does what I expect: each 14 | * callable is executed on its own thread and the results are 15 | * delivered to the subscriber upon completion. 16 | * 17 | * In contrast to Async.start(), fromCallable() doesn't start 18 | * executing the source functions until the subscriber subscribes. 19 | * 20 | * Also in contrast to Async.start() which, when it works, sees 21 | * values delivered to the subscriber on the main thread, 22 | * fromCallable() ends up delivering them on one of the threads 23 | * that is emitting source values. 24 | */ 25 | object Example12_UsingAsyncFromCallable extends App { 26 | 27 | def sleepThenGenerate(n: Int)() = { 28 | debug("Generating", n) 29 | Thread.sleep(800) 30 | debug("Sending", n) 31 | n 32 | } 33 | 34 | val asyncGenerator1: Observable[Int] = Async.fromCallable(sleepThenGenerate(1) _) 35 | val asyncGenerator2: Observable[Int] = Async.fromCallable(sleepThenGenerate(2) _) 36 | 37 | val shiftedUp1 = asyncGenerator1.debug("Generated").map(shiftUp).debug("Shifted Up #1") 38 | val shiftedUp2 = asyncGenerator2.debug("Generated").map(shiftUp).debug("Shifted Up #2") 39 | 40 | val zipped = shiftedUp1.zip(shiftedUp2).map(_._1).debug("Zipped") 41 | 42 | val shiftedDown = zipped.map(shiftDown).debug("Shifted Down") 43 | 44 | Thread.sleep(100) 45 | println("Subscribing...") 46 | shiftedDown.subscribe( 47 | onNext = debug("Received", _), 48 | onCompleted = () => {println("Completed")}, 49 | onError = (t) => {} 50 | ) 51 | 52 | // The built in Schedulers use daemon threads, so you need to make the main thread stick around or you won't see anything 53 | Thread.sleep(2000) 54 | } 55 | -------------------------------------------------------------------------------- /src/main/scala/com/grahamlea/examples/rxjava/threading/package.scala: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2014 Belmont Technology Pty Ltd. All rights reserved. 2 | package com.grahamlea.examples.rxjava 3 | 4 | import rx.lang.scala.Observable 5 | 6 | package object threading { 7 | 8 | val maxNumber = 5 9 | 10 | val generator: Observable[Int] = Observable.from(1 to maxNumber).debug("Generated") 11 | 12 | implicit class ObservableWithDebug(observable: Observable[Int]) { 13 | def debug(message: String) = { 14 | observable.doOnNext(value => { 15 | threading.debug(message, value, if (value > maxNumber) shiftDown(value) else value) 16 | }) 17 | } 18 | } 19 | 20 | val shiftUp: (Int) => Int = (i: Int) => {Thread.sleep(25); i + (maxNumber * 2) } 21 | 22 | val shiftDown: (Int) => Int = (i: Int) => {Thread.sleep(25); i - (maxNumber * 2) } 23 | 24 | def debug(message: String, value: Int): Unit = debug(message, value, value) 25 | 26 | def debug(message: String, value: Int, indent: Int): Unit = { 27 | printf("%30s %-14s %" + (indent * 4) + "s%n", "[" + Thread.currentThread().getName + "]", message, value) 28 | } 29 | } 30 | --------------------------------------------------------------------------------