├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── rx │ │ └── quasar │ │ ├── BlockingObservable.java │ │ ├── ChannelObservable.java │ │ ├── NewFiberScheduler.java │ │ ├── OnSubscribeFromChannel.java │ │ └── RxSuspendableClassifier.java └── resources │ └── META-INF │ ├── services │ └── co.paralleluniverse.fibers.instrument.SuspendableClassifier │ ├── suspendable-supers │ └── suspendables └── test └── java └── rx └── quasar ├── AbstractSchedulerConcurrencyTests.java ├── AbstractSchedulerTests.java ├── BlockingObservableTest.java ├── ChannelObservableTest.java ├── NewFiberSchedulerTest.java └── TestException.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | 27 | # OS generated files # 28 | ###################### 29 | .DS_Store* 30 | ehthumbs.db 31 | Icon? 32 | Thumbs.db 33 | 34 | # Editor Files # 35 | ################ 36 | *~ 37 | *.swp 38 | 39 | # Gradle Files # 40 | ################ 41 | .gradle 42 | .gradletasknamecache 43 | .m2 44 | 45 | # Build output directies 46 | target/ 47 | build/ 48 | 49 | # IntelliJ specific files/directories 50 | out 51 | .idea 52 | *.ipr 53 | *.iws 54 | *.iml 55 | atlassian-ide-plugin.xml 56 | 57 | # Eclipse specific files/directories 58 | .classpath 59 | .project 60 | .settings 61 | .metadata 62 | bin/ 63 | 64 | # NetBeans specific files/directories 65 | .nbattrs 66 | /.nb-gradle/profiles/private/ 67 | .nb-gradle-properties 68 | 69 | # Scala build 70 | *.cache 71 | /.nb-gradle/private/ 72 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk7 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to RxJava 2 | 3 | If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request (on a branch other than `master` or `gh-pages`). 4 | 5 | When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. 6 | 7 | ## License 8 | 9 | By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxJava/blob/master/LICENSE 10 | 11 | All files are released with the Apache 2.0 license. 12 | 13 | If you are adding a new file it should have a header like this: 14 | 15 | ``` 16 | /** 17 | * Copyright 2014 Netflix, Inc. 18 | * 19 | * Licensed under the Apache License, Version 2.0 (the "License"); 20 | * you may not use this file except in compliance with the License. 21 | * You may obtain a copy of the License at 22 | * 23 | * http://www.apache.org/licenses/LICENSE-2.0 24 | * 25 | * Unless required by applicable law or agreed to in writing, software 26 | * distributed under the License is distributed on an "AS IS" BASIS, 27 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 28 | * See the License for the specific language governing permissions and 29 | * limitations under the License. 30 | */ 31 | ``` 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 Netflix, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RxQuasar 2 | 3 | This project is no longer maintained. Please use [Quasar's Reactive Streams support](http://blog.paralleluniverse.co/2015/06/25/reactive-streams/) to integrate Quasar with RxJava. 4 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { jcenter() } 3 | dependencies { classpath 'com.netflix.nebula:gradle-rxjava-project-plugin:2.+' } 4 | } 5 | 6 | apply plugin: 'rxjava-project' 7 | apply plugin: 'java' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_1_6 10 | targetCompatibility = JavaVersion.VERSION_1_7 11 | 12 | configurations { 13 | quasar 14 | } 15 | 16 | dependencies { 17 | compile 'io.reactivex:rxjava:1.0.+' 18 | compile 'co.paralleluniverse:quasar-core:0.6.0' 19 | quasar 'co.paralleluniverse:quasar-core:0.6.0' 20 | testCompile 'junit:junit-dep:4.10' 21 | testCompile 'org.mockito:mockito-core:1.8.5' 22 | } 23 | 24 | tasks.withType(Test) { 25 | // systemProperty 'co.paralleluniverse.fibers.verifyInstrumentation', 'true' 26 | jvmArgs "-javaagent:${configurations.quasar.iterator().next()}" // =vdmc (verbose, debug, allow monitors, check class) 27 | } 28 | 29 | tasks.withType(JavaExec) { 30 | // systemProperty 'co.paralleluniverse.fibers.verifyInstrumentation', 'true' 31 | jvmArgs "-javaagent:${configurations.quasar.iterator().next()}" // =vdmc (verbose, debug, allow monitors, check class) 32 | } 33 | 34 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReactiveX/RxQuasar/5925cf3d2e2035b818a77eab67e4a575ef14cf93/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Dec 13 00:16:29 PST 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='rxquasar' 2 | -------------------------------------------------------------------------------- /src/main/java/rx/quasar/BlockingObservable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import java.util.concurrent.Future; 19 | import java.util.concurrent.TimeUnit; 20 | import java.util.concurrent.atomic.AtomicBoolean; 21 | import java.util.concurrent.atomic.AtomicReference; 22 | 23 | import rx.Observable; 24 | import rx.Observer; 25 | import rx.Subscriber; 26 | import rx.Subscription; 27 | import rx.exceptions.Exceptions; 28 | import rx.functions.Action1; 29 | import rx.functions.Func1; 30 | import rx.observers.SafeSubscriber; 31 | import co.paralleluniverse.fibers.SuspendExecution; 32 | import co.paralleluniverse.fibers.Suspendable; 33 | import co.paralleluniverse.strands.AbstractFuture; 34 | import co.paralleluniverse.strands.ConditionSynchronizer; 35 | import co.paralleluniverse.strands.SimpleConditionSynchronizer; 36 | import co.paralleluniverse.strands.Strand; 37 | import co.paralleluniverse.strands.channels.Channels; 38 | import co.paralleluniverse.strands.channels.DelegatingReceivePort; 39 | import co.paralleluniverse.strands.channels.ProducerException; 40 | import co.paralleluniverse.strands.channels.ReceivePort; 41 | 42 | /** 43 | * An extension of {@link Observable} that provides blocking operators, compatible with both threads and fibers. 44 | *

45 | * You construct a BlockingObservable from an 46 | * Observable with {@link #from(Observable)}. 47 | *

48 | * The documentation for this interface makes use of a form of marble diagram 49 | * that has been modified to illustrate blocking operators. The following legend 50 | * explains these marble diagrams: 51 | *

52 | * 53 | *

54 | * For more information see the 55 | * Blocking 56 | * Observable Operators page at the RxJava Wiki. 57 | * 58 | * @param 59 | */ 60 | public class BlockingObservable { 61 | private static final int BUFFER_SIZE = 10; 62 | private final Observable o; 63 | 64 | private BlockingObservable(Observable o) { 65 | this.o = o; 66 | } 67 | 68 | /** 69 | * Convert an Observable into a BlockingObservable. 70 | */ 71 | public static BlockingObservable from(final Observable o) { 72 | return new BlockingObservable(o); 73 | } 74 | 75 | /** 76 | * Used for protecting against errors being thrown from {@link Subscriber} implementations and ensuring onNext/onError/onCompleted contract 77 | * compliance. 78 | *

79 | * See https://github.com/Netflix/RxJava/issues/216 for discussion on 80 | * "Guideline 6.4: Protect calls to user code from within an operator" 81 | */ 82 | private Subscription protectivelyWrapAndSubscribe(Subscriber observer) { 83 | return o.subscribe(new SafeSubscriber(observer)); 84 | } 85 | 86 | /** 87 | * Invoke a method on each item emitted by the {@link Observable}; block 88 | * until the Observable completes. 89 | *

90 | * NOTE: This will block even if the Observable is asynchronous. 91 | *

92 | * This is similar to {@link Observable#subscribe(Subscriber)}, but it blocks. 93 | * Because it blocks it does not need the {@link Subscriber#onCompleted()} or {@link Subscriber#onError(Throwable)} methods. 94 | *

95 | * 96 | * 97 | * @param onNext 98 | * the {@link Action1} to invoke for every item emitted by the {@link Observable} 99 | * @throws RuntimeException 100 | * if an error occurs 101 | * @see RxJava Wiki: forEach() 102 | */ 103 | @Suspendable 104 | public void forEach(final Action1 onNext) { 105 | try { 106 | final AtomicBoolean done = new AtomicBoolean(false); 107 | final ConditionSynchronizer sync = new SimpleConditionSynchronizer(this); 108 | final AtomicReference exceptionFromOnError = new AtomicReference(); 109 | 110 | /** 111 | * Wrapping since raw functions provided by the user are being invoked. 112 | * 113 | * See https://github.com/Netflix/RxJava/issues/216 for discussion on 114 | * "Guideline 6.4: Protect calls to user code from within an operator" 115 | */ 116 | protectivelyWrapAndSubscribe(new Subscriber() { 117 | @Override 118 | public void onCompleted() { 119 | done.set(true); 120 | sync.signalAll(); 121 | } 122 | 123 | @Override 124 | public void onError(Throwable e) { 125 | /* 126 | * If we receive an onError event we set the reference on the 127 | * outer thread so we can git it and throw after the 128 | * latch.await(). 129 | * 130 | * We do this instead of throwing directly since this may be on 131 | * a different thread and the latch is still waiting. 132 | */ 133 | exceptionFromOnError.set(e); 134 | done.set(true); 135 | sync.signalAll(); 136 | } 137 | 138 | @Override 139 | public void onNext(T args) { 140 | onNext.call(args); 141 | } 142 | }); 143 | // block until the subscription completes and then return 144 | try { 145 | final Object token = sync.register(); 146 | try { 147 | for (int i = 0; !done.get(); i++) 148 | sync.await(i); 149 | } finally { 150 | sync.unregister(token); 151 | } 152 | } catch (InterruptedException e) { 153 | // set the interrupted flag again so callers can still get it 154 | // for more information see https://github.com/Netflix/RxJava/pull/147#issuecomment-13624780 155 | Strand.currentStrand().interrupt(); 156 | // using Runtime so it is not checked 157 | throw new RuntimeException("Interrupted while waiting for subscription to complete.", e); 158 | } 159 | 160 | if (exceptionFromOnError.get() != null) { 161 | if (exceptionFromOnError.get() instanceof RuntimeException) { 162 | throw (RuntimeException) exceptionFromOnError.get(); 163 | } else { 164 | throw new RuntimeException(exceptionFromOnError.get()); 165 | } 166 | } 167 | } catch (SuspendExecution e) { 168 | throw new AssertionError(e); 169 | } 170 | } 171 | 172 | /** 173 | * Returns an {@link ReceivePort} that receives all items emitted by a 174 | * specified {@link Observable}. 175 | * 176 | * @return an {@link ReceivePort} that receives all items emitted by a 177 | * specified {@link Observable}. 178 | */ 179 | public ReceivePort toChannel() { 180 | return ChannelObservable.subscribe(BUFFER_SIZE, Channels.OverflowPolicy.BLOCK, o); 181 | } 182 | 183 | /** 184 | * Returns the first item emitted by a specified {@link Observable}, or 185 | * IllegalArgumentException if source contains no elements. 186 | * 187 | * @return the first item emitted by the source {@link Observable} 188 | * @throws IllegalArgumentException 189 | * if source contains no elements 190 | * @see RxJava Wiki: first() 191 | * @see MSDN: Observable.First 192 | */ 193 | @Suspendable 194 | public T first() { 195 | return from(o.first()).single(); 196 | } 197 | 198 | /** 199 | * Returns the first item emitted by a specified {@link Observable} that 200 | * matches a predicate, or IllegalArgumentException if no such 201 | * item is emitted. 202 | * 203 | * @param predicate 204 | * a predicate function to evaluate items emitted by the {@link Observable} 205 | * @return the first item emitted by the {@link Observable} that matches the 206 | * predicate 207 | * @throws IllegalArgumentException 208 | * if no such items are emitted 209 | * @see RxJava Wiki: first() 210 | * @see MSDN: Observable.First 211 | */ 212 | @Suspendable 213 | public T first(Func1 predicate) { 214 | return from(o.first(predicate)).single(); 215 | } 216 | 217 | /** 218 | * Returns the first item emitted by a specified {@link Observable}, or a 219 | * default value if no items are emitted. 220 | * 221 | * @param defaultValue 222 | * a default value to return if the {@link Observable} emits no items 223 | * @return the first item emitted by the {@link Observable}, or the default 224 | * value if no items are emitted 225 | * @see RxJava Wiki: firstOrDefault() 226 | * @see MSDN: Observable.FirstOrDefault 227 | */ 228 | @Suspendable 229 | public T firstOrDefault(T defaultValue) { 230 | return from(o.take(1)).singleOrDefault(defaultValue); 231 | } 232 | 233 | /** 234 | * Returns the first item emitted by a specified {@link Observable} that 235 | * matches a predicate, or a default value if no such items are emitted. 236 | * 237 | * @param defaultValue 238 | * a default value to return if the {@link Observable} emits no matching items 239 | * @param predicate 240 | * a predicate function to evaluate items emitted by the {@link Observable} 241 | * @return the first item emitted by the {@link Observable} that matches the 242 | * predicate, or the default value if no matching items are emitted 243 | * @see RxJava Wiki: firstOrDefault() 244 | * @see MSDN: Observable.FirstOrDefault 245 | */ 246 | @Suspendable 247 | public T firstOrDefault(T defaultValue, Func1 predicate) { 248 | return from(o.filter(predicate)).firstOrDefault(defaultValue); 249 | } 250 | 251 | /** 252 | * Returns the last item emitted by a specified {@link Observable}, or 253 | * throws IllegalArgumentException if it emits no items. 254 | *

255 | * 256 | * 257 | * @return the last item emitted by the source {@link Observable} 258 | * @throws IllegalArgumentException 259 | * if source contains no elements 260 | * @see RxJava Wiki: last() 261 | * @see MSDN: Observable.Last 262 | */ 263 | @Suspendable 264 | public T last() { 265 | return from(o.last()).single(); 266 | } 267 | 268 | /** 269 | * Returns the last item emitted by a specified {@link Observable} that 270 | * matches a predicate, or throws IllegalArgumentException if 271 | * it emits no such items. 272 | *

273 | * 274 | * 275 | * @param predicate 276 | * a predicate function to evaluate items emitted by the {@link Observable} 277 | * @return the last item emitted by the {@link Observable} that matches the 278 | * predicate 279 | * @throws IllegalArgumentException 280 | * if no such items are emitted 281 | * @see RxJava Wiki: last() 282 | * @see MSDN: Observable.Last 283 | */ 284 | @Suspendable 285 | public T last(final Func1 predicate) { 286 | return from(o.last(predicate)).single(); 287 | } 288 | 289 | /** 290 | * Returns the last item emitted by a specified {@link Observable}, or a 291 | * default value if no items are emitted. 292 | *

293 | * 294 | * 295 | * @param defaultValue 296 | * a default value to return if the {@link Observable} emits no items 297 | * @return the last item emitted by the {@link Observable}, or the default 298 | * value if no items are emitted 299 | * @see RxJava Wiki: lastOrDefault() 300 | * @see MSDN: Observable.LastOrDefault 301 | */ 302 | @Suspendable 303 | public T lastOrDefault(T defaultValue) { 304 | return from(o.takeLast(1)).singleOrDefault(defaultValue); 305 | } 306 | 307 | /** 308 | * Returns the last item emitted by a specified {@link Observable} that 309 | * matches a predicate, or a default value if no such items are emitted. 310 | *

311 | * 312 | * 313 | * @param defaultValue 314 | * a default value to return if the {@link Observable} emits no matching items 315 | * @param predicate 316 | * a predicate function to evaluate items emitted by the {@link Observable} 317 | * @return the last item emitted by the {@link Observable} that matches the 318 | * predicate, or the default value if no matching items are emitted 319 | * @see RxJava Wiki: lastOrDefault() 320 | * @see MSDN: Observable.LastOrDefault 321 | */ 322 | @Suspendable 323 | public T lastOrDefault(T defaultValue, Func1 predicate) { 324 | return from(o.filter(predicate)).lastOrDefault(defaultValue); 325 | } 326 | 327 | /** 328 | * Returns an {@link Iterable} that always returns the item most recently 329 | * emitted by an {@link Observable}. 330 | *

331 | * 332 | * 333 | * @param initialValue 334 | * the initial value that will be yielded by the {@link Iterable} sequence if the {@link Observable} has not yet emitted an item 335 | * @return an {@link Iterable} that on each iteration returns the item that 336 | * the {@link Observable} has most recently emitted 337 | * @see RxJava wiki: mostRecent() 338 | * @see MSDN: Observable.MostRecent 339 | */ 340 | public ReceivePort mostRecent(T initialValue) { 341 | return new RecentReceivePort(ChannelObservable.subscribe(1, Channels.OverflowPolicy.DISPLACE, o), initialValue); 342 | } 343 | 344 | /** 345 | * Returns an {@link Iterable} that blocks until the {@link Observable} emits another item, then returns that item. 346 | *

347 | * 348 | * 349 | * @return an {@link Iterable} that blocks upon each iteration until the {@link Observable} emits a new item, whereupon the Iterable returns that item 350 | * @see RxJava Wiki: next() 351 | * @see MSDN: Observable.Next 352 | */ 353 | public ReceivePort next() { 354 | return ChannelObservable.subscribe(1, Channels.OverflowPolicy.DISPLACE, o); 355 | } 356 | 357 | /** 358 | * Returns the latest item emitted by the underlying Observable, waiting if 359 | * necessary for one to become available. 360 | *

361 | * If the underlying Observable produces items faster than the 362 | * Iterator.next() takes them, onNext events might 363 | * be skipped, but onError or onCompleted events 364 | * are not. 365 | *

366 | * Note also that an onNext() directly followed by 367 | * onCompleted() might hide the onNext() event. 368 | * 369 | * @return the receive port 370 | * @see RxJava wiki: latest() 371 | * @see MSDN: Observable.Latest 372 | */ 373 | public ReceivePort latest() { 374 | return new LatestReceivePort(ChannelObservable.subscribe(1, Channels.OverflowPolicy.DISPLACE, o)); 375 | } 376 | 377 | /** 378 | * If the {@link Observable} completes after emitting a single item, return 379 | * that item, otherwise throw an IllegalArgumentException. 380 | *

381 | * 382 | * 383 | * @return the single item emitted by the {@link Observable} 384 | * @see RxJava Wiki: single() 385 | * @see MSDN: Observable.Single 386 | */ 387 | @Suspendable 388 | public T single() { 389 | try { 390 | return from(o.single()).toChannel().receive(); 391 | } catch (ProducerException e) { 392 | throw Exceptions.propagate(e.getCause()); 393 | } catch (InterruptedException e) { 394 | Strand.currentStrand().interrupt(); 395 | throw Exceptions.propagate(e); 396 | } catch (SuspendExecution e) { 397 | throw new AssertionError(e); 398 | } 399 | } 400 | 401 | /** 402 | * If the {@link Observable} completes after emitting a single item that 403 | * matches a given predicate, return that item, otherwise throw an 404 | * IllegalArgumentException. 405 | *

406 | * 407 | * 408 | * @param predicate 409 | * a predicate function to evaluate items emitted by the {@link Observable} 410 | * @return the single item emitted by the source {@link Observable} that 411 | * matches the predicate 412 | * @see RxJava Wiki: single() 413 | * @see MSDN: Observable.Single 414 | */ 415 | @Suspendable 416 | public T single(Func1 predicate) { 417 | try { 418 | return from(o.single(predicate)).toChannel().receive(); 419 | } catch (ProducerException e) { 420 | throw Exceptions.propagate(e.getCause()); 421 | } catch (InterruptedException e) { 422 | Strand.currentStrand().interrupt(); 423 | throw Exceptions.propagate(e); 424 | } catch (SuspendExecution e) { 425 | throw new AssertionError(e); 426 | } 427 | } 428 | 429 | /** 430 | * If the {@link Observable} completes after emitting a single item, return 431 | * that item; if it emits more than one item, throw an 432 | * IllegalArgumentException; if it emits no items, return a 433 | * default value. 434 | *

435 | * 436 | * 437 | * @param defaultValue 438 | * a default value to return if the {@link Observable} emits no items 439 | * @return the single item emitted by the {@link Observable}, or the default 440 | * value if no items are emitted 441 | * @see RxJava Wiki: singleOrDefault() 442 | * @see MSDN: Observable.SingleOrDefault 443 | */ 444 | @Suspendable 445 | public T singleOrDefault(T defaultValue) { 446 | try { 447 | ReceivePort c = this.toChannel(); 448 | 449 | T result = c.receive(); 450 | if (result == null) 451 | return defaultValue; 452 | if (c.receive() != null) { 453 | throw new IllegalArgumentException("Sequence contains too many elements"); 454 | } 455 | return result; 456 | } catch (ProducerException e) { 457 | throw Exceptions.propagate(e.getCause()); 458 | } catch (InterruptedException e) { 459 | Strand.currentStrand().interrupt(); 460 | throw Exceptions.propagate(e); 461 | } catch (SuspendExecution e) { 462 | throw new AssertionError(e); 463 | } 464 | } 465 | 466 | /** 467 | * If the {@link Observable} completes after emitting a single item that 468 | * matches a predicate, return that item; if it emits more than one such 469 | * item, throw an IllegalArgumentException; if it emits no 470 | * items, return a default value. 471 | *

472 | * 473 | * 474 | * @param defaultValue 475 | * a default value to return if the {@link Observable} emits no matching items 476 | * @param predicate 477 | * a predicate function to evaluate items emitted by the {@link Observable} 478 | * @return the single item emitted by the {@link Observable} that matches 479 | * the predicate, or the default value if no such items are emitted 480 | * @see RxJava Wiki: singleOrDefault() 481 | * @see MSDN: Observable.SingleOrDefault 482 | */ 483 | @Suspendable 484 | public T singleOrDefault(T defaultValue, Func1 predicate) { 485 | return from(o.filter(predicate)).singleOrDefault(defaultValue); 486 | } 487 | 488 | /** 489 | * Returns a {@link Future} representing the single value emitted by an {@link Observable}. 490 | *

491 | * toFuture() throws an exception if the Observable emits more 492 | * than one item. If the Observable may emit more than item, use {@link Observable#toList toList()}.toFuture(). 493 | *

494 | * 495 | * 496 | * @return a {@link Future} that expects a single item to be emitted by the source {@link Observable} 497 | * @see RxJava Wiki: toFuture() 498 | */ 499 | public Future toFuture() { 500 | return new AbstractFuture() { 501 | final AtomicReference val = new AtomicReference(); 502 | 503 | { 504 | o.subscribe(new Observer() { 505 | @Override 506 | public void onCompleted() { 507 | set(val.get()); 508 | } 509 | 510 | @Override 511 | public void onError(Throwable e) { 512 | setException(e); 513 | } 514 | 515 | @Override 516 | public void onNext(T t) { 517 | if (!val.compareAndSet(null, t)) 518 | setException(new IllegalStateException("Observable.toFuture() only supports sequences with a single value.")); 519 | } 520 | }); 521 | } 522 | }; 523 | } 524 | 525 | private static class RecentReceivePort extends DelegatingReceivePort { 526 | private V value; 527 | 528 | public RecentReceivePort(ReceivePort target, V initialValue) { 529 | super(target); 530 | this.value = initialValue; 531 | } 532 | 533 | @Override 534 | public V receive(long timeout, TimeUnit unit) { 535 | return getValue(); 536 | } 537 | 538 | @Override 539 | public V receive() { 540 | return getValue(); 541 | } 542 | 543 | @Override 544 | public V tryReceive() { 545 | return getValue(); 546 | } 547 | 548 | private V getValue() { 549 | V v = super.tryReceive(); 550 | if (v == null) { 551 | if (isClosed()) 552 | return null; 553 | return value; 554 | } 555 | this.value = v; 556 | return v; 557 | } 558 | } 559 | 560 | private static class LatestReceivePort extends DelegatingReceivePort { 561 | private V value; 562 | 563 | public LatestReceivePort(ReceivePort target) { 564 | super(target); 565 | this.value = null; 566 | } 567 | 568 | @Override 569 | public V receive() throws SuspendExecution, InterruptedException { 570 | V v = getValue(); 571 | if (v == null && !isClosed()) { 572 | this.value = super.receive(); 573 | return value; 574 | } 575 | return v; 576 | } 577 | 578 | @Override 579 | public V receive(long timeout, TimeUnit unit) throws SuspendExecution, InterruptedException { 580 | V v = getValue(); 581 | if (v == null && !isClosed()) { 582 | this.value = super.receive(timeout, unit); 583 | return value; 584 | } 585 | return v; 586 | } 587 | 588 | @Override 589 | public V tryReceive() { 590 | return getValue(); 591 | } 592 | 593 | @Override 594 | public boolean isClosed() { 595 | return super.isClosed() && value == null; 596 | } 597 | 598 | private V getValue() { 599 | V v = tryReceive(); 600 | if (v == null) { 601 | v = value; 602 | if (isClosed()) { 603 | this.value = null; 604 | return null; 605 | } 606 | return v; 607 | } 608 | this.value = v; 609 | return v; 610 | } 611 | } 612 | } 613 | -------------------------------------------------------------------------------- /src/main/java/rx/quasar/ChannelObservable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */package rx.quasar; 16 | 17 | import java.util.concurrent.ExecutionException; 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.TimeoutException; 20 | 21 | import rx.Observable; 22 | import rx.Observer; 23 | import rx.Scheduler; 24 | import co.paralleluniverse.fibers.FiberAsync; 25 | import co.paralleluniverse.fibers.SuspendExecution; 26 | import co.paralleluniverse.fibers.Suspendable; 27 | import co.paralleluniverse.strands.Strand; 28 | import co.paralleluniverse.strands.channels.Channel; 29 | import co.paralleluniverse.strands.channels.Channels; 30 | import co.paralleluniverse.strands.channels.ReceivePort; 31 | import co.paralleluniverse.strands.channels.SendPort; 32 | 33 | /** 34 | * This class contains static methods that connect {@link Observable}s and {@link Channel}s. 35 | */ 36 | public final class ChannelObservable { 37 | private ChannelObservable() { 38 | } 39 | 40 | /** 41 | * Converts an {@link Iterable} sequence into an Observable that emits each message received on the channel. 42 | *

43 | * 44 | *

45 | * @param channel 46 | * the source {@link ReceivePort} 47 | * @param 48 | * the type of messages on the channel and the type of items to be 49 | * emitted by the resulting Observable 50 | * @return an Observable that emits each message received on the source {@link ReceivePort} 51 | * @see RxJava Wiki: from() 52 | */ 53 | public static Observable from(ReceivePort channel) { 54 | return Observable.create(new OnSubscribeFromChannel(channel)); 55 | } 56 | 57 | /** 58 | * Converts an {@link Iterable} sequence into an Observable that operates on the specified 59 | * scheduler, emitting each message received on the channel. 60 | *

61 | * 62 | *

63 | * @param channel 64 | * the source {@link ReceivePort} 65 | * @param scheduler 66 | * the scheduler on which the Observable is to emit the messages received on the channel 67 | * @param 68 | * the type of messages on the channel and the type of items to be 69 | * emitted by the resulting Observable 70 | * @return an Observable that emits each message received on the source {@link ReceivePort}, on the 71 | * specified scheduler 72 | * @see RxJava Wiki: from() 73 | * @see MSDN: Observable.ToObservable 74 | */ 75 | public static Observable from(ReceivePort channel, Scheduler scheduler) { 76 | return Observable.create(new OnSubscribeFromChannel(channel)).subscribeOn(scheduler); 77 | } 78 | 79 | /** 80 | * Converts a {@link SendPort} channel into an {@link Observer}. 81 | *

82 | * @param the type of messages that can be sent to the channel and the type of items to be 83 | * received by the Observer 84 | * @param channel the target {@link SendPort} 85 | * @return the observer 86 | */ 87 | public static Observer to(final SendPort channel) { 88 | return new Observer() { 89 | 90 | @Override 91 | @Suspendable 92 | public void onNext(T t) { 93 | try { 94 | channel.send(t); 95 | } catch (InterruptedException ex) { 96 | Strand.interrupted(); 97 | } catch (SuspendExecution ex) { 98 | throw new AssertionError(ex); 99 | } 100 | } 101 | 102 | @Override 103 | public void onCompleted() { 104 | channel.close(); 105 | } 106 | 107 | @Override 108 | public void onError(Throwable e) { 109 | channel.close(e); 110 | } 111 | }; 112 | } 113 | 114 | /** 115 | * Creates a {@link ReceivePort} subscribed to an {@link Observable}. 116 | *

117 | * @param the type of messages emitted by the observable and received on the channel. 118 | * @param bufferSize the channel's buffer size 119 | * @param policy the channel's {@link Channels.OverflowPolicy} 120 | * @param o the observable 121 | * @return A new channel with the given buffer size and overflow policy that will receive all events emitted by the observable. 122 | */ 123 | public static ReceivePort subscribe(int bufferSize, Channels.OverflowPolicy policy, Observable o) { 124 | final Channel channel = Channels.newChannel(bufferSize, policy); 125 | 126 | o.subscribe(new Observer() { 127 | @Override 128 | @Suspendable 129 | public void onNext(T t) { 130 | try { 131 | channel.send(t); 132 | } catch (InterruptedException ex) { 133 | Strand.interrupted(); 134 | } catch (SuspendExecution ex) { 135 | throw new AssertionError(ex); 136 | } 137 | } 138 | 139 | @Override 140 | public void onCompleted() { 141 | channel.close(); 142 | } 143 | 144 | @Override 145 | public void onError(Throwable e) { 146 | channel.close(e); 147 | } 148 | }); 149 | return channel; 150 | } 151 | 152 | /** 153 | * Takes an observable that generates at most one value, blocks until it completes and returns the result. 154 | * If the observable completes before a value has been emitted, this method returns {@code null}. 155 | * It the observable fails, this function throws an {@link ExecutionException} that wraps the observable's exception. 156 | * 157 | * @param o the observable 158 | * @return the observable's result, or {@code null} if the observable completes before a value is emitted. 159 | * @throws ExecutionException if the observable fails 160 | */ 161 | public static T get(final Observable o) throws ExecutionException, SuspendExecution, InterruptedException { 162 | return new AsyncObservable(o).run(); 163 | } 164 | 165 | /** 166 | * Takes an observable that generates at most one value, blocks until it completes or the timeout expires, and returns the result. 167 | * If the observable completes before a value has been emitted, this method returns {@code null}. 168 | * It the observable fails, this function throws an {@link ExecutionException} that wraps the observable's exception. 169 | * 170 | * @param o the observable 171 | * @param timeout the maximum time this method will blcok 172 | * @param unit the timeout's time unit 173 | * @return the observable's result, or {@code null} if the observable completes before a value is emitted. 174 | * @throws ExecutionException if the observable fails 175 | * @throws TimeoutException if the timeout expires before the observable completes 176 | */ 177 | public static T get(final Observable o, long timeout, TimeUnit unit) throws ExecutionException, SuspendExecution, InterruptedException, TimeoutException { 178 | return new AsyncObservable(o).run(timeout, unit); 179 | } 180 | 181 | private static class AsyncObservable extends FiberAsync implements Observer { 182 | private final Observable o; 183 | 184 | public AsyncObservable(Observable o) { 185 | this.o = o; 186 | } 187 | 188 | @Override 189 | protected void requestAsync() { 190 | o.subscribe(this); 191 | } 192 | 193 | @Override 194 | public void onNext(T t) { 195 | if (isCompleted()) 196 | throw new IllegalStateException("Operation already completed"); 197 | asyncCompleted(t); 198 | } 199 | 200 | @Override 201 | public void onError(Throwable e) { 202 | if (isCompleted()) 203 | throw new IllegalStateException("Operation already completed"); 204 | asyncFailed(e); 205 | } 206 | 207 | @Override 208 | public void onCompleted() { 209 | if (!isCompleted()) 210 | asyncCompleted(null); 211 | } 212 | 213 | @Override 214 | protected ExecutionException wrapException(Throwable t) { 215 | return new ExecutionException(t); 216 | } 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /src/main/java/rx/quasar/NewFiberScheduler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.atomic.AtomicReference; 20 | 21 | import rx.Scheduler; 22 | import rx.Subscription; 23 | import rx.functions.Action0; 24 | import rx.subscriptions.CompositeSubscription; 25 | import rx.subscriptions.Subscriptions; 26 | import co.paralleluniverse.fibers.DefaultFiberScheduler; 27 | import co.paralleluniverse.fibers.Fiber; 28 | import co.paralleluniverse.fibers.FiberScheduler; 29 | import co.paralleluniverse.fibers.SuspendExecution; 30 | import co.paralleluniverse.strands.SuspendableRunnable; 31 | 32 | /** 33 | * Schedules work on a new fiber. 34 | */ 35 | public class NewFiberScheduler extends Scheduler { 36 | private final static NewFiberScheduler DEFAULT_INSTANCE = new NewFiberScheduler(); 37 | 38 | public static NewFiberScheduler getDefaultInstance() { 39 | return DEFAULT_INSTANCE; 40 | } 41 | 42 | private final FiberScheduler fiberScheduler; 43 | 44 | public NewFiberScheduler(FiberScheduler fiberScheduler) { 45 | if(fiberScheduler == null) 46 | throw new IllegalArgumentException("Fiber scheduler is null"); 47 | if(fiberScheduler == DefaultFiberScheduler.getInstance() && DEFAULT_INSTANCE != null) 48 | throw new IllegalArgumentException("Fiber scheduler is the default FiberScheduler; use getDefaultInstance()"); 49 | this.fiberScheduler = fiberScheduler; 50 | } 51 | 52 | private NewFiberScheduler() { 53 | this(DefaultFiberScheduler.getInstance()); 54 | } 55 | 56 | @Override 57 | public Worker createWorker() { 58 | return new EventLoopScheduler(); 59 | } 60 | 61 | 62 | private class EventLoopScheduler extends Scheduler.Worker implements Subscription { 63 | private final CompositeSubscription innerSubscription = new CompositeSubscription(); 64 | 65 | private EventLoopScheduler() { 66 | } 67 | 68 | @Override 69 | public Subscription schedule(final Action0 action) { 70 | if (innerSubscription.isUnsubscribed()) { 71 | // don't schedule, we are unsubscribed 72 | return Subscriptions.empty(); 73 | } 74 | 75 | final AtomicReference sf = new AtomicReference(); 76 | final Subscription s = Subscriptions.from(new Fiber(fiberScheduler, new SuspendableRunnable() { 77 | 78 | @Override 79 | public void run() throws SuspendExecution { 80 | try { 81 | if (innerSubscription.isUnsubscribed()) { 82 | return; 83 | } 84 | action.call(); 85 | } finally { 86 | // remove the subscription now that we're completed 87 | Subscription s = sf.get(); 88 | if (s != null) { 89 | innerSubscription.remove(s); 90 | } 91 | } 92 | } 93 | }).start()); 94 | 95 | sf.set(s); 96 | innerSubscription.add(s); 97 | return Subscriptions.create(new Action0() { 98 | 99 | @Override 100 | public void call() { 101 | s.unsubscribe(); 102 | innerSubscription.remove(s); 103 | } 104 | 105 | }); 106 | } 107 | 108 | @Override 109 | public Subscription schedule(final Action0 action, final long delayTime, final TimeUnit unit) { 110 | final AtomicReference sf = new AtomicReference(); 111 | 112 | final Subscription s = Subscriptions.from(new Fiber(fiberScheduler, new SuspendableRunnable() { 113 | 114 | @Override 115 | public void run() throws InterruptedException, SuspendExecution { 116 | Fiber.sleep(delayTime, unit); 117 | try { 118 | if (innerSubscription.isUnsubscribed()) { 119 | return; 120 | } 121 | // now that the delay is past schedule the work to be done for real on the UI thread 122 | action.call(); 123 | } finally { 124 | // remove the subscription now that we're completed 125 | Subscription s = sf.get(); 126 | if (s != null) { 127 | innerSubscription.remove(s); 128 | } 129 | } 130 | } 131 | }).start()); 132 | 133 | sf.set(s); 134 | innerSubscription.add(s); 135 | return Subscriptions.create(new Action0() { 136 | 137 | @Override 138 | public void call() { 139 | s.unsubscribe(); 140 | innerSubscription.remove(s); 141 | } 142 | 143 | }); 144 | } 145 | 146 | @Override 147 | public void unsubscribe() { 148 | innerSubscription.unsubscribe(); 149 | } 150 | 151 | @Override 152 | public boolean isUnsubscribed() { 153 | return innerSubscription.isUnsubscribed(); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/rx/quasar/OnSubscribeFromChannel.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import rx.Observable.OnSubscribe; 19 | import rx.Subscriber; 20 | import co.paralleluniverse.fibers.Suspendable; 21 | import co.paralleluniverse.strands.channels.ReceivePort; 22 | 23 | /** 24 | * Converts a {@link ReceivePort} into an Observable that emits each message received on the channel. 25 | *

26 | * 27 | */ 28 | public final class OnSubscribeFromChannel implements OnSubscribe { 29 | 30 | final ReceivePort channel; 31 | 32 | public OnSubscribeFromChannel(ReceivePort channel) { 33 | this.channel = channel; 34 | } 35 | 36 | @Override 37 | @Suspendable 38 | public void call(Subscriber o) { 39 | for (;;) { 40 | T m; 41 | 42 | try { 43 | m = channel.receive(); 44 | if (m == null) 45 | break; 46 | if (o.isUnsubscribed()) { 47 | return; 48 | } 49 | } catch (InterruptedException e) { 50 | break; 51 | } catch (Exception e) { 52 | o.onError(e); 53 | return; 54 | } 55 | 56 | o.onNext(m); 57 | } 58 | 59 | o.onCompleted(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/rx/quasar/RxSuspendableClassifier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import java.util.Arrays; 19 | import java.util.HashSet; 20 | import java.util.Set; 21 | 22 | import co.paralleluniverse.fibers.instrument.MethodDatabase; 23 | import co.paralleluniverse.fibers.instrument.SimpleSuspendableClassifier; 24 | import co.paralleluniverse.fibers.instrument.SuspendableClassifier; 25 | 26 | public class RxSuspendableClassifier implements SuspendableClassifier { 27 | private static final Set CORE_PACKAGES = new HashSet(Arrays.asList(new String[]{ 28 | "rx", "rx.joins", "rx.observables", "rx.observers", "rx.operators", "rx.plugins", "rx.schedulers", 29 | "rx.subjects", "rx.subscriptions", "rx.functions", "rx.util", "rx.util.functions" 30 | })); 31 | 32 | private static final Set EXCEPTIONS = new HashSet(Arrays.asList(new String[]{ 33 | "rx/observers/SynchronizedObserver", 34 | "rx/schedulers/AbstractSchedulerTests$ConcurrentObserverValidator", 35 | })); 36 | 37 | private static final Set OBSERVER_METHODS = new HashSet(Arrays.asList(new String[]{ 38 | "onNext(Ljava/lang/Object;)V", "onCompleted()V", "onError(Ljava/lang/Throwable;)V" 39 | })); 40 | 41 | private static final String FUNCTION_METHOD = "call"; 42 | 43 | @Override 44 | public MethodDatabase.SuspendableType isSuspendable(MethodDatabase db, String className, String superClassName, String[] interfaces, String methodName, String methodDesc, String methodSignature, String[] methodExceptions) { 45 | MethodDatabase.SuspendableType s = null; 46 | if (isCoreRx(className) && !EXCEPTIONS.contains(className)) { 47 | if (isObserverImplementation(db, className, superClassName, interfaces, methodName, methodDesc)) 48 | s = MethodDatabase.SuspendableType.SUSPENDABLE; 49 | else if (isUtilFunction(db, className, superClassName, interfaces, methodName, methodDesc)) 50 | s = MethodDatabase.SuspendableType.SUSPENDABLE; 51 | } 52 | if (s == null 53 | && methodName.equals("call") 54 | && (className.startsWith("rx/functions/Func") || className.startsWith("rx/functions/Action") 55 | || className.startsWith("rx/util/functions/Func") || className.startsWith("rx/util/functions/Action"))) { 56 | s = MethodDatabase.SuspendableType.SUSPENDABLE_SUPER; 57 | } 58 | // System.out.println("-- " + className + "." + methodName + ": " + s); 59 | return s; 60 | } 61 | 62 | private boolean isCoreRx(String className) { 63 | return CORE_PACKAGES.contains(packageOf(className)); 64 | } 65 | 66 | private static boolean isObserverImplementation(MethodDatabase db, String className, String superClassName, String[] interfaces, String methodName, String methodDesc) { 67 | return !className.equals("rx/Observer") 68 | && OBSERVER_METHODS.contains(methodName + methodDesc) 69 | && SimpleSuspendableClassifier.extendsOrImplements("rx/Observer", db, className, superClassName, interfaces); 70 | } 71 | 72 | private static boolean isUtilFunction(MethodDatabase db, String className, String superClassName, String[] interfaces, String methodName, String methodDesc) { 73 | return (className.startsWith("rx/functions/Functions") || className.startsWith("rx/functions/Actions") 74 | || className.startsWith("rx/util/functions/Functions") || className.startsWith("rx/util/functions/Actions")) 75 | && methodName.equals(FUNCTION_METHOD) 76 | && (SimpleSuspendableClassifier.extendsOrImplements("rx/functions/Function", db, className, superClassName, interfaces) 77 | || SimpleSuspendableClassifier.extendsOrImplements("rx/functions/Action", db, className, superClassName, interfaces) 78 | || SimpleSuspendableClassifier.extendsOrImplements("rx/util/functions/Function", db, className, superClassName, interfaces) 79 | || SimpleSuspendableClassifier.extendsOrImplements("rx/util/functions/Action", db, className, superClassName, interfaces)); 80 | } 81 | 82 | private static String packageOf(String className) { 83 | return className.substring(0, Math.max(0, className.lastIndexOf('/'))).replace('/', '.'); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/co.paralleluniverse.fibers.instrument.SuspendableClassifier: -------------------------------------------------------------------------------- 1 | rx.quasar.RxSuspendableClassifier 2 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/suspendable-supers: -------------------------------------------------------------------------------- 1 | rx.Observer.onNext 2 | rx.Observer.onError 3 | rx.Observer.onCompleted -------------------------------------------------------------------------------- /src/main/resources/META-INF/suspendables: -------------------------------------------------------------------------------- 1 | rx.Observable.subscribe 2 | rx.Observable$2.call 3 | rx.Observable.unsafeSubscribe 4 | rx.internal.operators.OperatorSubscribeOn$1$1.call 5 | rx.internal.operators.OperatorSubscribeOn$1$1$1.onNext 6 | rx.internal.operators.OperatorSubscribeOn$1$1$1.onError 7 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/AbstractSchedulerConcurrencyTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertFalse; 20 | import static org.junit.Assert.assertTrue; 21 | import static org.junit.Assert.fail; 22 | 23 | import java.util.concurrent.CountDownLatch; 24 | import java.util.concurrent.TimeUnit; 25 | import java.util.concurrent.atomic.AtomicBoolean; 26 | import java.util.concurrent.atomic.AtomicInteger; 27 | 28 | import org.junit.Test; 29 | 30 | import rx.Observable; 31 | import rx.Observable.OnSubscribe; 32 | import rx.Scheduler; 33 | import rx.Scheduler.Worker; 34 | import rx.Subscriber; 35 | import rx.Subscription; 36 | import rx.functions.Action0; 37 | import rx.functions.Action1; 38 | import rx.functions.Func1; 39 | import rx.subscriptions.Subscriptions; 40 | 41 | /** 42 | * Base tests for schedulers that involve threads (concurrency). 43 | * 44 | * These can only run on Schedulers that launch threads since they expect async/concurrent behavior. 45 | * 46 | * The Current/Immediate schedulers will not work with these tests. 47 | */ 48 | public abstract class AbstractSchedulerConcurrencyTests extends AbstractSchedulerTests { 49 | 50 | /** 51 | * Bug report: https://github.com/ReactiveX/RxJava/issues/431 52 | */ 53 | @Test 54 | public final void testUnSubscribeForScheduler() throws InterruptedException { 55 | final AtomicInteger countReceived = new AtomicInteger(); 56 | final AtomicInteger countGenerated = new AtomicInteger(); 57 | final CountDownLatch latch = new CountDownLatch(1); 58 | 59 | Observable.interval(50, TimeUnit.MILLISECONDS) 60 | .map(new Func1() { 61 | @Override 62 | public Long call(Long aLong) { 63 | countGenerated.incrementAndGet(); 64 | return aLong; 65 | } 66 | }) 67 | .subscribeOn(getScheduler()) 68 | .observeOn(getScheduler()) 69 | .subscribe(new Subscriber() { 70 | @Override 71 | public void onCompleted() { 72 | System.out.println("--- completed"); 73 | } 74 | 75 | @Override 76 | public void onError(Throwable e) { 77 | System.out.println("--- onError"); 78 | } 79 | 80 | @Override 81 | public void onNext(Long args) { 82 | if (countReceived.incrementAndGet() == 2) { 83 | unsubscribe(); 84 | latch.countDown(); 85 | } 86 | System.out.println("==> Received " + args); 87 | } 88 | }); 89 | 90 | latch.await(1000, TimeUnit.MILLISECONDS); 91 | 92 | System.out.println("----------- it thinks it is finished ------------------ "); 93 | Thread.sleep(100); 94 | 95 | assertEquals(2, countGenerated.get()); 96 | } 97 | 98 | @Test 99 | public void testUnsubscribeRecursiveScheduleFromOutside() throws InterruptedException { 100 | final CountDownLatch latch = new CountDownLatch(1); 101 | final CountDownLatch unsubscribeLatch = new CountDownLatch(1); 102 | final AtomicInteger counter = new AtomicInteger(); 103 | final Worker inner = getScheduler().createWorker(); 104 | 105 | inner.schedule(new Action0() { 106 | 107 | @Override 108 | public void call() { 109 | inner.schedule(new Action0() { 110 | 111 | int i = 0; 112 | 113 | @Override 114 | public void call() { 115 | System.out.println("Run: " + i++); 116 | if (i == 10) { 117 | latch.countDown(); 118 | try { 119 | // wait for unsubscribe to finish so we are not racing it 120 | unsubscribeLatch.await(); 121 | } catch (InterruptedException e) { 122 | // we expect the countDown if unsubscribe is not working 123 | // or to be interrupted if unsubscribe is successful since 124 | // the unsubscribe will interrupt it as it is calling Future.cancel(true) 125 | // so we will ignore the stacktrace 126 | } 127 | } 128 | 129 | counter.incrementAndGet(); 130 | inner.schedule(this); 131 | } 132 | }); 133 | } 134 | 135 | }); 136 | 137 | latch.await(); 138 | inner.unsubscribe(); 139 | unsubscribeLatch.countDown(); 140 | Thread.sleep(200); // let time pass to see if the scheduler is still doing work 141 | assertEquals(10, counter.get()); 142 | } 143 | 144 | @Test 145 | public void testUnsubscribeRecursiveScheduleFromInside() throws InterruptedException { 146 | final CountDownLatch unsubscribeLatch = new CountDownLatch(1); 147 | final AtomicInteger counter = new AtomicInteger(); 148 | final Worker inner = getScheduler().createWorker(); 149 | inner.schedule(new Action0() { 150 | 151 | @Override 152 | public void call() { 153 | inner.schedule(new Action0() { 154 | 155 | int i = 0; 156 | 157 | @Override 158 | public void call() { 159 | System.out.println("Run: " + i++); 160 | if (i == 10) { 161 | inner.unsubscribe(); 162 | } 163 | 164 | counter.incrementAndGet(); 165 | inner.schedule(this); 166 | } 167 | }); 168 | } 169 | 170 | }); 171 | 172 | unsubscribeLatch.countDown(); 173 | Thread.sleep(200); // let time pass to see if the scheduler is still doing work 174 | assertEquals(10, counter.get()); 175 | } 176 | 177 | @Test 178 | public void testUnsubscribeRecursiveScheduleWithDelay() throws InterruptedException { 179 | final CountDownLatch latch = new CountDownLatch(1); 180 | final CountDownLatch unsubscribeLatch = new CountDownLatch(1); 181 | final AtomicInteger counter = new AtomicInteger(); 182 | final Worker inner = getScheduler().createWorker(); 183 | inner.schedule(new Action0() { 184 | 185 | @Override 186 | public void call() { 187 | inner.schedule(new Action0() { 188 | 189 | long i = 1L; 190 | 191 | @Override 192 | public void call() { 193 | if (i++ == 10) { 194 | latch.countDown(); 195 | try { 196 | // wait for unsubscribe to finish so we are not racing it 197 | unsubscribeLatch.await(); 198 | } catch (InterruptedException e) { 199 | // we expect the countDown if unsubscribe is not working 200 | // or to be interrupted if unsubscribe is successful since 201 | // the unsubscribe will interrupt it as it is calling Future.cancel(true) 202 | // so we will ignore the stacktrace 203 | } 204 | } 205 | 206 | counter.incrementAndGet(); 207 | inner.schedule(this, 10, TimeUnit.MILLISECONDS); 208 | } 209 | }, 10, TimeUnit.MILLISECONDS); 210 | } 211 | }); 212 | 213 | latch.await(); 214 | inner.unsubscribe(); 215 | unsubscribeLatch.countDown(); 216 | Thread.sleep(200); // let time pass to see if the scheduler is still doing work 217 | assertEquals(10, counter.get()); 218 | } 219 | 220 | @Test 221 | public void recursionFromOuterActionAndUnsubscribeInside() throws InterruptedException { 222 | final CountDownLatch latch = new CountDownLatch(1); 223 | final Worker inner = getScheduler().createWorker(); 224 | inner.schedule(new Action0() { 225 | 226 | int i = 0; 227 | 228 | @Override 229 | public void call() { 230 | i++; 231 | if (i % 100000 == 0) { 232 | System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory()); 233 | } 234 | if (i < 1000000L) { 235 | inner.schedule(this); 236 | } else { 237 | latch.countDown(); 238 | } 239 | } 240 | }); 241 | 242 | latch.await(); 243 | } 244 | 245 | @Test 246 | public void testRecursion() throws InterruptedException { 247 | final CountDownLatch latch = new CountDownLatch(1); 248 | final Worker inner = getScheduler().createWorker(); 249 | inner.schedule(new Action0() { 250 | 251 | private long i = 0; 252 | 253 | @Override 254 | public void call() { 255 | i++; 256 | if (i % 100000 == 0) { 257 | System.out.println(i + " Total Memory: " + Runtime.getRuntime().totalMemory() + " Free: " + Runtime.getRuntime().freeMemory()); 258 | } 259 | if (i < 1000000L) { 260 | inner.schedule(this); 261 | } else { 262 | latch.countDown(); 263 | } 264 | } 265 | }); 266 | 267 | latch.await(); 268 | } 269 | 270 | @Test 271 | public void testRecursionAndOuterUnsubscribe() throws InterruptedException { 272 | // use latches instead of Thread.sleep 273 | final CountDownLatch latch = new CountDownLatch(10); 274 | final CountDownLatch completionLatch = new CountDownLatch(1); 275 | 276 | Observable obs = Observable.create(new OnSubscribe() { 277 | @Override 278 | public void call(final Subscriber observer) { 279 | final Worker inner = getScheduler().createWorker(); 280 | inner.schedule(new Action0() { 281 | @Override 282 | public void call() { 283 | observer.onNext(42); 284 | latch.countDown(); 285 | 286 | // this will recursively schedule this task for execution again 287 | inner.schedule(this); 288 | } 289 | }); 290 | 291 | observer.add(Subscriptions.create(new Action0() { 292 | 293 | @Override 294 | public void call() { 295 | inner.unsubscribe(); 296 | observer.onCompleted(); 297 | completionLatch.countDown(); 298 | } 299 | 300 | })); 301 | 302 | } 303 | }); 304 | 305 | final AtomicInteger count = new AtomicInteger(); 306 | final AtomicBoolean completed = new AtomicBoolean(false); 307 | Subscription subscribe = obs.subscribe(new Subscriber() { 308 | @Override 309 | public void onCompleted() { 310 | System.out.println("Completed"); 311 | completed.set(true); 312 | } 313 | 314 | @Override 315 | public void onError(Throwable e) { 316 | System.out.println("Error"); 317 | } 318 | 319 | @Override 320 | public void onNext(Integer args) { 321 | count.incrementAndGet(); 322 | System.out.println(args); 323 | } 324 | }); 325 | 326 | if (!latch.await(5000, TimeUnit.MILLISECONDS)) { 327 | fail("Timed out waiting on onNext latch"); 328 | } 329 | 330 | // now unsubscribe and ensure it stops the recursive loop 331 | subscribe.unsubscribe(); 332 | System.out.println("unsubscribe"); 333 | 334 | if (!completionLatch.await(5000, TimeUnit.MILLISECONDS)) { 335 | fail("Timed out waiting on completion latch"); 336 | } 337 | 338 | // the count can be 10 or higher due to thread scheduling of the unsubscribe vs the scheduler looping to emit the count 339 | assertTrue(count.get() >= 10); 340 | assertTrue(completed.get()); 341 | } 342 | 343 | @Test 344 | public final void testSubscribeWithScheduler() throws InterruptedException { 345 | final Scheduler scheduler = getScheduler(); 346 | 347 | final AtomicInteger count = new AtomicInteger(); 348 | 349 | Observable o1 = Observable. just(1, 2, 3, 4, 5); 350 | 351 | o1.subscribe(new Action1() { 352 | 353 | @Override 354 | public void call(Integer t) { 355 | System.out.println("Thread: " + Thread.currentThread().getName()); 356 | System.out.println("t: " + t); 357 | count.incrementAndGet(); 358 | } 359 | }); 360 | 361 | // the above should be blocking so we should see a count of 5 362 | assertEquals(5, count.get()); 363 | 364 | count.set(0); 365 | 366 | // now we'll subscribe with a scheduler and it should be async 367 | 368 | final String currentThreadName = Thread.currentThread().getName(); 369 | 370 | // latches for deterministically controlling the test below across threads 371 | final CountDownLatch latch = new CountDownLatch(5); 372 | final CountDownLatch first = new CountDownLatch(1); 373 | 374 | o1.subscribeOn(scheduler).subscribe(new Action1() { 375 | 376 | @Override 377 | public void call(Integer t) { 378 | try { 379 | // we block the first one so we can assert this executes asynchronously with a count 380 | first.await(1000, TimeUnit.SECONDS); 381 | } catch (InterruptedException e) { 382 | throw new RuntimeException("The latch should have released if we are async.", e); 383 | } 384 | 385 | assertFalse(Thread.currentThread().getName().equals(currentThreadName)); 386 | System.out.println("Thread: " + Thread.currentThread().getName()); 387 | System.out.println("t: " + t); 388 | count.incrementAndGet(); 389 | latch.countDown(); 390 | } 391 | }); 392 | 393 | // assert we are async 394 | assertEquals(0, count.get()); 395 | // release the latch so it can go forward 396 | first.countDown(); 397 | 398 | // wait for all 5 responses 399 | latch.await(); 400 | assertEquals(5, count.get()); 401 | } 402 | 403 | } 404 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/AbstractSchedulerTests.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertTrue; 20 | import static org.junit.Assert.fail; 21 | import static org.mockito.Mockito.doAnswer; 22 | import static org.mockito.Mockito.inOrder; 23 | import static org.mockito.Mockito.mock; 24 | import static org.mockito.Mockito.times; 25 | import static org.mockito.Mockito.verify; 26 | 27 | import java.util.Arrays; 28 | import java.util.List; 29 | import java.util.concurrent.CountDownLatch; 30 | import java.util.concurrent.TimeUnit; 31 | import java.util.concurrent.atomic.AtomicInteger; 32 | import java.util.concurrent.atomic.AtomicReference; 33 | 34 | import org.junit.Test; 35 | import org.mockito.InOrder; 36 | import org.mockito.invocation.InvocationOnMock; 37 | import org.mockito.stubbing.Answer; 38 | 39 | import rx.Observable; 40 | import rx.Observable.OnSubscribe; 41 | import rx.Scheduler; 42 | import rx.Subscriber; 43 | import rx.functions.Action0; 44 | import rx.functions.Action1; 45 | import rx.functions.Func1; 46 | 47 | /** 48 | * Base tests for all schedulers including Immediate/Current. 49 | */ 50 | public abstract class AbstractSchedulerTests { 51 | 52 | /** 53 | * The scheduler to test 54 | */ 55 | protected abstract Scheduler getScheduler(); 56 | 57 | @Test 58 | public void testNestedActions() throws InterruptedException { 59 | Scheduler scheduler = getScheduler(); 60 | final Scheduler.Worker inner = scheduler.createWorker(); 61 | final CountDownLatch latch = new CountDownLatch(1); 62 | 63 | final Action0 firstStepStart = mock(Action0.class); 64 | final Action0 firstStepEnd = mock(Action0.class); 65 | 66 | final Action0 secondStepStart = mock(Action0.class); 67 | final Action0 secondStepEnd = mock(Action0.class); 68 | 69 | final Action0 thirdStepStart = mock(Action0.class); 70 | final Action0 thirdStepEnd = mock(Action0.class); 71 | 72 | final Action0 firstAction = new Action0() { 73 | @Override 74 | public void call() { 75 | firstStepStart.call(); 76 | firstStepEnd.call(); 77 | latch.countDown(); 78 | } 79 | }; 80 | final Action0 secondAction = new Action0() { 81 | @Override 82 | public void call() { 83 | secondStepStart.call(); 84 | inner.schedule(firstAction); 85 | secondStepEnd.call(); 86 | 87 | } 88 | }; 89 | final Action0 thirdAction = new Action0() { 90 | @Override 91 | public void call() { 92 | thirdStepStart.call(); 93 | inner.schedule(secondAction); 94 | thirdStepEnd.call(); 95 | } 96 | }; 97 | 98 | InOrder inOrder = inOrder(firstStepStart, firstStepEnd, secondStepStart, secondStepEnd, thirdStepStart, thirdStepEnd); 99 | 100 | inner.schedule(thirdAction); 101 | 102 | latch.await(); 103 | 104 | inOrder.verify(thirdStepStart, times(1)).call(); 105 | inOrder.verify(thirdStepEnd, times(1)).call(); 106 | inOrder.verify(secondStepStart, times(1)).call(); 107 | inOrder.verify(secondStepEnd, times(1)).call(); 108 | inOrder.verify(firstStepStart, times(1)).call(); 109 | inOrder.verify(firstStepEnd, times(1)).call(); 110 | } 111 | 112 | @Test 113 | public final void testNestedScheduling() { 114 | 115 | Observable ids = Observable.from(Arrays.asList(1, 2)).subscribeOn(getScheduler()); 116 | 117 | Observable m = ids.flatMap(new Func1>() { 118 | 119 | @Override 120 | public Observable call(Integer id) { 121 | return Observable.from(Arrays.asList("a-" + id, "b-" + id)).subscribeOn(getScheduler()) 122 | .map(new Func1() { 123 | 124 | @Override 125 | public String call(String s) { 126 | return "names=>" + s; 127 | } 128 | }); 129 | } 130 | 131 | }); 132 | 133 | List strings = m.toList().toBlocking().last(); 134 | 135 | assertEquals(4, strings.size()); 136 | // because flatMap does a merge there is no guarantee of order 137 | assertTrue(strings.contains("names=>a-1")); 138 | assertTrue(strings.contains("names=>a-2")); 139 | assertTrue(strings.contains("names=>b-1")); 140 | assertTrue(strings.contains("names=>b-2")); 141 | } 142 | 143 | /** 144 | * The order of execution is nondeterministic. 145 | * 146 | * @throws InterruptedException 147 | */ 148 | @SuppressWarnings("rawtypes") 149 | @Test 150 | public final void testSequenceOfActions() throws InterruptedException { 151 | final Scheduler scheduler = getScheduler(); 152 | final Scheduler.Worker inner = scheduler.createWorker(); 153 | 154 | final CountDownLatch latch = new CountDownLatch(2); 155 | final Action0 first = mock(Action0.class); 156 | final Action0 second = mock(Action0.class); 157 | 158 | // make it wait until both the first and second are called 159 | doAnswer(new Answer() { 160 | 161 | @Override 162 | public Object answer(InvocationOnMock invocation) throws Throwable { 163 | try { 164 | return invocation.getMock(); 165 | } finally { 166 | latch.countDown(); 167 | } 168 | } 169 | }).when(first).call(); 170 | doAnswer(new Answer() { 171 | 172 | @Override 173 | public Object answer(InvocationOnMock invocation) throws Throwable { 174 | try { 175 | return invocation.getMock(); 176 | } finally { 177 | latch.countDown(); 178 | } 179 | } 180 | }).when(second).call(); 181 | 182 | inner.schedule(first); 183 | inner.schedule(second); 184 | 185 | latch.await(); 186 | 187 | verify(first, times(1)).call(); 188 | verify(second, times(1)).call(); 189 | 190 | } 191 | 192 | @Test 193 | public void testSequenceOfDelayedActions() throws InterruptedException { 194 | Scheduler scheduler = getScheduler(); 195 | final Scheduler.Worker inner = scheduler.createWorker(); 196 | 197 | final CountDownLatch latch = new CountDownLatch(1); 198 | final Action0 first = mock(Action0.class); 199 | final Action0 second = mock(Action0.class); 200 | 201 | inner.schedule(new Action0() { 202 | @Override 203 | public void call() { 204 | inner.schedule(first, 30, TimeUnit.MILLISECONDS); 205 | inner.schedule(second, 10, TimeUnit.MILLISECONDS); 206 | inner.schedule(new Action0() { 207 | 208 | @Override 209 | public void call() { 210 | latch.countDown(); 211 | } 212 | }, 40, TimeUnit.MILLISECONDS); 213 | } 214 | }); 215 | 216 | latch.await(); 217 | InOrder inOrder = inOrder(first, second); 218 | 219 | inOrder.verify(second, times(1)).call(); 220 | inOrder.verify(first, times(1)).call(); 221 | 222 | } 223 | 224 | @Test 225 | public void testMixOfDelayedAndNonDelayedActions() throws InterruptedException { 226 | Scheduler scheduler = getScheduler(); 227 | final Scheduler.Worker inner = scheduler.createWorker(); 228 | 229 | final CountDownLatch latch = new CountDownLatch(1); 230 | final Action0 first = mock(Action0.class); 231 | final Action0 second = mock(Action0.class); 232 | final Action0 third = mock(Action0.class); 233 | final Action0 fourth = mock(Action0.class); 234 | 235 | inner.schedule(new Action0() { 236 | @Override 237 | public void call() { 238 | inner.schedule(first); 239 | inner.schedule(second, 300, TimeUnit.MILLISECONDS); 240 | inner.schedule(third, 100, TimeUnit.MILLISECONDS); 241 | inner.schedule(fourth); 242 | inner.schedule(new Action0() { 243 | 244 | @Override 245 | public void call() { 246 | latch.countDown(); 247 | } 248 | }, 400, TimeUnit.MILLISECONDS); 249 | } 250 | }); 251 | 252 | latch.await(); 253 | InOrder inOrder = inOrder(first, second, third, fourth); 254 | 255 | inOrder.verify(first, times(1)).call(); 256 | inOrder.verify(third, times(1)).call(); 257 | inOrder.verify(second, times(1)).call(); 258 | 259 | inOrder = inOrder(first, second, third, fourth); 260 | 261 | inOrder.verify(fourth, times(1)).call(); 262 | inOrder.verify(third, times(1)).call(); 263 | inOrder.verify(second, times(1)).call(); 264 | } 265 | 266 | @Test 267 | public final void testRecursiveExecution() throws InterruptedException { 268 | final Scheduler scheduler = getScheduler(); 269 | final Scheduler.Worker inner = scheduler.createWorker(); 270 | final AtomicInteger i = new AtomicInteger(); 271 | final CountDownLatch latch = new CountDownLatch(1); 272 | inner.schedule(new Action0() { 273 | 274 | @Override 275 | public void call() { 276 | if (i.incrementAndGet() < 100) { 277 | inner.schedule(this); 278 | } else { 279 | latch.countDown(); 280 | } 281 | } 282 | }); 283 | 284 | latch.await(); 285 | assertEquals(100, i.get()); 286 | } 287 | 288 | @Test 289 | public final void testRecursiveExecutionWithDelayTime() throws InterruptedException { 290 | Scheduler scheduler = getScheduler(); 291 | final Scheduler.Worker inner = scheduler.createWorker(); 292 | final AtomicInteger i = new AtomicInteger(); 293 | final CountDownLatch latch = new CountDownLatch(1); 294 | 295 | inner.schedule(new Action0() { 296 | 297 | int state = 0; 298 | 299 | @Override 300 | public void call() { 301 | i.set(state); 302 | if (state++ < 100) { 303 | inner.schedule(this, 1, TimeUnit.MILLISECONDS); 304 | } else { 305 | latch.countDown(); 306 | } 307 | } 308 | 309 | }); 310 | 311 | latch.await(); 312 | assertEquals(100, i.get()); 313 | } 314 | 315 | @Test 316 | public final void testRecursiveSchedulerInObservable() { 317 | Observable obs = Observable.create(new OnSubscribe() { 318 | @Override 319 | public void call(final Subscriber observer) { 320 | final Scheduler.Worker inner = getScheduler().createWorker(); 321 | observer.add(inner); 322 | inner.schedule(new Action0() { 323 | int i = 0; 324 | 325 | @Override 326 | public void call() { 327 | if (i > 42) { 328 | observer.onCompleted(); 329 | return; 330 | } 331 | 332 | observer.onNext(i++); 333 | 334 | inner.schedule(this); 335 | } 336 | }); 337 | } 338 | }); 339 | 340 | final AtomicInteger lastValue = new AtomicInteger(); 341 | obs.toBlocking().forEach(new Action1() { 342 | 343 | @Override 344 | public void call(Integer v) { 345 | System.out.println("Value: " + v); 346 | lastValue.set(v); 347 | } 348 | }); 349 | 350 | assertEquals(42, lastValue.get()); 351 | } 352 | 353 | @Test 354 | public final void testConcurrentOnNextFailsValidation() throws InterruptedException { 355 | final int count = 10; 356 | final CountDownLatch latch = new CountDownLatch(count); 357 | Observable o = Observable.create(new OnSubscribe() { 358 | 359 | @Override 360 | public void call(final Subscriber observer) { 361 | for (int i = 0; i < count; i++) { 362 | final int v = i; 363 | new Thread(new Runnable() { 364 | 365 | @Override 366 | public void run() { 367 | observer.onNext("v: " + v); 368 | 369 | latch.countDown(); 370 | } 371 | }).start(); 372 | } 373 | } 374 | }); 375 | 376 | ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); 377 | // this should call onNext concurrently 378 | o.subscribe(observer); 379 | 380 | if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { 381 | fail("timed out"); 382 | } 383 | 384 | if (observer.error.get() == null) { 385 | fail("We expected error messages due to concurrency"); 386 | } 387 | } 388 | 389 | @Test 390 | public final void testObserveOn() throws InterruptedException { 391 | final Scheduler scheduler = getScheduler(); 392 | 393 | Observable o = Observable.just("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"); 394 | 395 | ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); 396 | 397 | o.observeOn(scheduler).subscribe(observer); 398 | 399 | if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { 400 | fail("timed out"); 401 | } 402 | 403 | if (observer.error.get() != null) { 404 | observer.error.get().printStackTrace(); 405 | fail("Error: " + observer.error.get().getMessage()); 406 | } 407 | } 408 | 409 | @Test 410 | public final void testSubscribeOnNestedConcurrency() throws InterruptedException { 411 | final Scheduler scheduler = getScheduler(); 412 | 413 | Observable o = Observable.just("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten") 414 | .flatMap(new Func1>() { 415 | 416 | @Override 417 | public Observable call(final String v) { 418 | return Observable.create(new OnSubscribe() { 419 | 420 | @Override 421 | public void call(Subscriber observer) { 422 | observer.onNext("value_after_map-" + v); 423 | observer.onCompleted(); 424 | } 425 | }).subscribeOn(scheduler); 426 | } 427 | }); 428 | 429 | ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); 430 | 431 | o.subscribe(observer); 432 | 433 | if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { 434 | fail("timed out"); 435 | } 436 | 437 | if (observer.error.get() != null) { 438 | observer.error.get().printStackTrace(); 439 | fail("Error: " + observer.error.get().getMessage()); 440 | } 441 | } 442 | 443 | /** 444 | * Used to determine if onNext is being invoked concurrently. 445 | * 446 | * @param 447 | */ 448 | private static class ConcurrentObserverValidator extends Subscriber { 449 | 450 | final AtomicInteger concurrentCounter = new AtomicInteger(); 451 | final AtomicReference error = new AtomicReference(); 452 | final CountDownLatch completed = new CountDownLatch(1); 453 | 454 | @Override 455 | public void onCompleted() { 456 | completed.countDown(); 457 | } 458 | 459 | @Override 460 | public void onError(Throwable e) { 461 | error.set(e); 462 | completed.countDown(); 463 | } 464 | 465 | @Override 466 | public void onNext(T args) { 467 | int count = concurrentCounter.incrementAndGet(); 468 | System.out.println("ConcurrentObserverValidator.onNext: " + args); 469 | if (count > 1) { 470 | onError(new RuntimeException("we should not have concurrent execution of onNext")); 471 | } 472 | try { 473 | try { 474 | // take some time so other onNext calls could pile up (I haven't yet thought of a way to do this without sleeping) 475 | Thread.sleep(50); 476 | } catch (InterruptedException e) { 477 | // ignore 478 | } 479 | } finally { 480 | concurrentCounter.decrementAndGet(); 481 | } 482 | } 483 | 484 | } 485 | 486 | } 487 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/BlockingObservableTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.fail; 20 | 21 | import java.util.NoSuchElementException; 22 | 23 | import org.junit.Assert; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | import org.mockito.Mock; 27 | import org.mockito.MockitoAnnotations; 28 | 29 | import rx.Observable; 30 | import rx.Subscriber; 31 | import rx.functions.Action1; 32 | import rx.functions.Func1; 33 | import co.paralleluniverse.strands.channels.ProducerException; 34 | import co.paralleluniverse.strands.channels.ReceivePort; 35 | 36 | public class BlockingObservableTest { 37 | 38 | @Mock 39 | Subscriber w; 40 | 41 | @Before 42 | public void before() { 43 | MockitoAnnotations.initMocks(this); 44 | } 45 | 46 | @Test 47 | public void testLast() { 48 | BlockingObservable obs = BlockingObservable.from(Observable.just("one", "two", "three")); 49 | 50 | assertEquals("three", obs.last()); 51 | } 52 | 53 | @Test(expected = NoSuchElementException.class) 54 | public void testLastEmptyObservable() { 55 | BlockingObservable obs = BlockingObservable.from(Observable.empty()); 56 | obs.last(); 57 | } 58 | 59 | @Test 60 | public void testLastOrDefault() { 61 | BlockingObservable observable = BlockingObservable.from(Observable.just(1, 0, -1)); 62 | int last = observable.lastOrDefault(-100, new Func1() { 63 | @Override 64 | public Boolean call(Integer args) { 65 | return args >= 0; 66 | } 67 | }); 68 | assertEquals(0, last); 69 | } 70 | 71 | @Test 72 | public void testLastOrDefault1() { 73 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 74 | assertEquals("three", observable.lastOrDefault("default")); 75 | } 76 | 77 | @Test 78 | public void testLastOrDefault2() { 79 | BlockingObservable observable = BlockingObservable.from(Observable.empty()); 80 | assertEquals("default", observable.lastOrDefault("default")); 81 | } 82 | 83 | @Test 84 | public void testLastOrDefaultWithPredicate() { 85 | BlockingObservable observable = BlockingObservable.from(Observable.just(1, 0, -1)); 86 | int last = observable.lastOrDefault(0, new Func1() { 87 | @Override 88 | public Boolean call(Integer args) { 89 | return args < 0; 90 | } 91 | }); 92 | 93 | assertEquals(-1, last); 94 | } 95 | 96 | @Test 97 | public void testLastOrDefaultWrongPredicate() { 98 | BlockingObservable observable = BlockingObservable.from(Observable.just(-1, -2, -3)); 99 | int last = observable.lastOrDefault(0, new Func1() { 100 | @Override 101 | public Boolean call(Integer args) { 102 | return args >= 0; 103 | } 104 | }); 105 | assertEquals(0, last); 106 | } 107 | 108 | @Test 109 | public void testLastWithPredicate() { 110 | BlockingObservable obs = BlockingObservable.from(Observable.just("one", "two", "three")); 111 | 112 | assertEquals("two", obs.last(new Func1() { 113 | @Override 114 | public Boolean call(String s) { 115 | return s.length() == 3; 116 | } 117 | })); 118 | } 119 | 120 | public void testSingle() { 121 | BlockingObservable observable = BlockingObservable.from(Observable.just("one")); 122 | assertEquals("one", observable.single()); 123 | } 124 | 125 | @Test 126 | public void testSingleDefault() { 127 | BlockingObservable observable = BlockingObservable.from(Observable.empty()); 128 | assertEquals("default", observable.singleOrDefault("default")); 129 | } 130 | 131 | @Test(expected = IllegalArgumentException.class) 132 | public void testSingleDefaultPredicateMatchesMoreThanOne() { 133 | BlockingObservable.from(Observable.just("one", "two")).singleOrDefault("default", new Func1() { 134 | @Override 135 | public Boolean call(String args) { 136 | return args.length() == 3; 137 | } 138 | }); 139 | } 140 | 141 | @Test 142 | public void testSingleDefaultPredicateMatchesNothing() { 143 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two")); 144 | String result = observable.singleOrDefault("default", new Func1() { 145 | @Override 146 | public Boolean call(String args) { 147 | return args.length() == 4; 148 | } 149 | }); 150 | assertEquals("default", result); 151 | } 152 | 153 | @Test(expected = IllegalArgumentException.class) 154 | public void testSingleDefaultWithMoreThanOne() { 155 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 156 | observable.singleOrDefault("default"); 157 | } 158 | 159 | @Test 160 | public void testSingleWithPredicateDefault() { 161 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "four")); 162 | assertEquals("four", observable.single(new Func1() { 163 | @Override 164 | public Boolean call(String s) { 165 | return s.length() == 4; 166 | } 167 | })); 168 | } 169 | 170 | @Test(expected = IllegalArgumentException.class) 171 | public void testSingleWrong() { 172 | BlockingObservable observable = BlockingObservable.from(Observable.just(1, 2)); 173 | observable.single(); 174 | } 175 | 176 | @Test(expected = NoSuchElementException.class) 177 | public void testSingleWrongPredicate() { 178 | BlockingObservable observable = BlockingObservable.from(Observable.just(-1)); 179 | observable.single(new Func1() { 180 | @Override 181 | public Boolean call(Integer args) { 182 | return args > 0; 183 | } 184 | }); 185 | } 186 | 187 | @Test 188 | public void testToChannel() throws Exception { 189 | BlockingObservable obs = BlockingObservable.from(Observable.just("one", "two", "three")); 190 | 191 | ReceivePort c = obs.toChannel(); 192 | 193 | assertEquals(false, c.isClosed()); 194 | assertEquals("one", c.receive()); 195 | 196 | assertEquals(false, c.isClosed()); 197 | assertEquals("two", c.receive()); 198 | 199 | assertEquals(false, c.isClosed()); 200 | assertEquals("three", c.receive()); 201 | 202 | assertEquals(true, c.isClosed()); 203 | 204 | } 205 | 206 | public void testToChannelNextOnly() throws Exception { 207 | BlockingObservable obs = BlockingObservable.from(Observable.just(1, 2, 3)); 208 | 209 | ReceivePort c = obs.toChannel(); 210 | 211 | Assert.assertEquals((Integer) 1, c.receive()); 212 | Assert.assertEquals((Integer) 2, c.receive()); 213 | Assert.assertEquals((Integer) 3, c.receive()); 214 | 215 | Assert.assertEquals(c.receive(), null); 216 | } 217 | 218 | public void testToChannelNextOnlyTwice() throws Exception { 219 | BlockingObservable obs = BlockingObservable.from(Observable.just(1, 2, 3)); 220 | 221 | ReceivePort c = obs.toChannel(); 222 | 223 | Assert.assertEquals((Integer) 1, c.receive()); 224 | Assert.assertEquals((Integer) 2, c.receive()); 225 | Assert.assertEquals((Integer) 3, c.receive()); 226 | 227 | Assert.assertEquals(c.receive(), null); 228 | Assert.assertEquals(c.receive(), null); 229 | } 230 | 231 | @Test 232 | public void testToChannelManyTimes() throws Exception { 233 | BlockingObservable obs = BlockingObservable.from(Observable.just(1, 2, 3)); 234 | 235 | for (int j = 0; j < 3; j++) { 236 | ReceivePort c = obs.toChannel(); 237 | 238 | Assert.assertFalse(c.isClosed()); 239 | Assert.assertEquals((Integer) 1, c.receive()); 240 | Assert.assertFalse(c.isClosed()); 241 | Assert.assertEquals((Integer) 2, c.receive()); 242 | Assert.assertFalse(c.isClosed()); 243 | Assert.assertEquals((Integer) 3, c.receive()); 244 | Assert.assertTrue(c.isClosed()); 245 | } 246 | } 247 | 248 | @Test(expected = TestException.class) 249 | public void testToChannelWithException() throws Throwable { 250 | BlockingObservable obs = BlockingObservable.from(Observable.create(new Observable.OnSubscribe() { 251 | 252 | @Override 253 | public void call(Subscriber observer) { 254 | observer.onNext("one"); 255 | observer.onError(new TestException()); 256 | } 257 | })); 258 | 259 | ReceivePort c = obs.toChannel(); 260 | 261 | assertEquals(false, c.isClosed()); 262 | assertEquals("one", c.receive()); 263 | 264 | try { 265 | c.receive(); 266 | } catch (ProducerException e) { 267 | throw e.getCause(); 268 | } 269 | } 270 | 271 | @Test 272 | public void testForEachWithError() { 273 | try { 274 | BlockingObservable.from(Observable.create(new Observable.OnSubscribe() { 275 | 276 | @Override 277 | public void call(final Subscriber observer) { 278 | new Thread(new Runnable() { 279 | 280 | @Override 281 | public void run() { 282 | observer.onNext("one"); 283 | observer.onNext("two"); 284 | observer.onNext("three"); 285 | observer.onCompleted(); 286 | } 287 | }).start(); 288 | } 289 | })).forEach(new Action1() { 290 | 291 | @Override 292 | public void call(String t1) { 293 | throw new RuntimeException("fail"); 294 | } 295 | }); 296 | fail("we expect an exception to be thrown"); 297 | } catch (Throwable e) { 298 | // do nothing as we expect this 299 | } 300 | } 301 | 302 | @Test 303 | public void testFirst() { 304 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 305 | assertEquals("one", observable.first()); 306 | } 307 | 308 | @Test(expected = NoSuchElementException.class) 309 | public void testFirstWithEmpty() { 310 | BlockingObservable.from(Observable.empty()).first(); 311 | } 312 | 313 | @Test 314 | public void testFirstWithPredicate() { 315 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 316 | String first = observable.first(new Func1() { 317 | @Override 318 | public Boolean call(String args) { 319 | return args.length() > 3; 320 | } 321 | }); 322 | assertEquals("three", first); 323 | } 324 | 325 | @Test(expected = NoSuchElementException.class) 326 | public void testFirstWithPredicateAndEmpty() { 327 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 328 | observable.first(new Func1() { 329 | @Override 330 | public Boolean call(String args) { 331 | return args.length() > 5; 332 | } 333 | }); 334 | } 335 | 336 | @Test 337 | public void testFirstOrDefault() { 338 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 339 | assertEquals("one", observable.firstOrDefault("default")); 340 | } 341 | 342 | @Test 343 | public void testFirstOrDefaultWithEmpty() { 344 | BlockingObservable observable = BlockingObservable.from(Observable.empty()); 345 | assertEquals("default", observable.firstOrDefault("default")); 346 | } 347 | 348 | @Test 349 | public void testFirstOrDefaultWithPredicate() { 350 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 351 | String first = observable.firstOrDefault("default", new Func1() { 352 | @Override 353 | public Boolean call(String args) { 354 | return args.length() > 3; 355 | } 356 | }); 357 | assertEquals("three", first); 358 | } 359 | 360 | @Test 361 | public void testFirstOrDefaultWithPredicateAndEmpty() { 362 | BlockingObservable observable = BlockingObservable.from(Observable.just("one", "two", "three")); 363 | String first = observable.firstOrDefault("default", new Func1() { 364 | @Override 365 | public Boolean call(String args) { 366 | return args.length() > 5; 367 | } 368 | }); 369 | assertEquals("default", first); 370 | } 371 | 372 | private static class TestException extends RuntimeException { 373 | private static final long serialVersionUID = 1L; 374 | } 375 | } 376 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/ChannelObservableTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import static org.hamcrest.CoreMatchers.equalTo; 19 | import static org.hamcrest.CoreMatchers.instanceOf; 20 | import static org.hamcrest.CoreMatchers.is; 21 | import static org.hamcrest.CoreMatchers.nullValue; 22 | import static org.junit.Assert.assertThat; 23 | import static org.junit.Assert.assertTrue; 24 | import static org.junit.Assert.fail; 25 | 26 | import java.util.ArrayList; 27 | import java.util.Arrays; 28 | import java.util.Queue; 29 | import java.util.concurrent.ConcurrentLinkedQueue; 30 | import java.util.concurrent.ExecutionException; 31 | import java.util.concurrent.atomic.AtomicBoolean; 32 | 33 | import org.junit.Test; 34 | 35 | import rx.Observable; 36 | import rx.Observer; 37 | import rx.subjects.PublishSubject; 38 | import co.paralleluniverse.fibers.Fiber; 39 | import co.paralleluniverse.fibers.SuspendExecution; 40 | import co.paralleluniverse.fibers.Suspendable; 41 | import co.paralleluniverse.strands.Strand; 42 | import co.paralleluniverse.strands.SuspendableCallable; 43 | import co.paralleluniverse.strands.channels.Channel; 44 | import co.paralleluniverse.strands.channels.Channels; 45 | import co.paralleluniverse.strands.channels.ProducerException; 46 | import co.paralleluniverse.strands.channels.ReceivePort; 47 | 48 | public class ChannelObservableTest { 49 | @Test 50 | public void testObservableFromChannel() throws Exception { 51 | final Channel c = Channels.newChannel(0); 52 | 53 | System.out.println("===== " + c); 54 | 55 | final Queue result = new ConcurrentLinkedQueue(); 56 | final AtomicBoolean completed = new AtomicBoolean(); 57 | 58 | ChannelObservable.from(c, NewFiberScheduler.getDefaultInstance()).subscribe(new Observer() { 59 | @Override 60 | @Suspendable 61 | public void onNext(String t) { 62 | try { 63 | System.out.println("GOT: " + t); 64 | assertTrue(Strand.isCurrentFiber()); 65 | Strand.sleep(100); 66 | result.add(t); 67 | } catch (InterruptedException e) { 68 | } catch (SuspendExecution e) { 69 | throw new AssertionError(e); 70 | } 71 | } 72 | 73 | @Override 74 | public void onCompleted() { 75 | completed.set(true); 76 | } 77 | 78 | @Override 79 | public void onError(Throwable e) { 80 | e.printStackTrace(); 81 | fail(); 82 | } 83 | }); 84 | 85 | c.send("a"); 86 | c.send("b"); 87 | c.send("c"); 88 | c.close(); 89 | 90 | Thread.sleep(500); 91 | 92 | assertThat(new ArrayList(result), equalTo(Arrays.asList("a", "b", "c"))); 93 | assertThat(completed.get(), is(true)); 94 | } 95 | 96 | @Test 97 | public void testObserverChannel() throws Exception { 98 | final Channel c = Channels.newChannel(10); // must use a buffer, otherwise will block on subscribe 99 | 100 | System.out.println("===== " + c); 101 | 102 | Observable.from(Arrays.asList("a", "b", "c")).subscribe(ChannelObservable.to(c)); 103 | 104 | assertThat(c.receive(), equalTo("a")); 105 | assertThat(c.receive(), equalTo("b")); 106 | assertThat(c.receive(), equalTo("c")); 107 | assertThat(c.receive(), is(nullValue())); 108 | } 109 | 110 | @Test 111 | public void testObserverChannel2() throws Exception { 112 | ReceivePort c = ChannelObservable.subscribe(10, Channels.OverflowPolicy.BLOCK, Observable.from(Arrays.asList("a", "b", "c"))); 113 | 114 | assertThat(c.receive(), equalTo("a")); 115 | assertThat(c.receive(), equalTo("b")); 116 | assertThat(c.receive(), equalTo("c")); 117 | assertThat(c.receive(), is(nullValue())); 118 | } 119 | 120 | @Test 121 | public void testObserverChannelWithError() throws Exception { 122 | PublishSubject o = PublishSubject.create(); 123 | ReceivePort c = ChannelObservable.subscribe(10, Channels.OverflowPolicy.BLOCK, o); 124 | 125 | o.onNext("a"); 126 | o.onError(new TestException()); 127 | o.onNext("c"); 128 | 129 | assertThat(c.receive(), equalTo("a")); 130 | try { 131 | c.receive(); 132 | fail(); 133 | } catch (ProducerException e) { 134 | assertThat(e.getCause(), instanceOf(TestException.class)); 135 | } 136 | assertThat(c.isClosed(), is(true)); 137 | } 138 | 139 | @Test 140 | public void whenGetThenBlockAndReturnResult() throws Exception { 141 | final PublishSubject o = PublishSubject.create(); 142 | 143 | Fiber f = new Fiber(new SuspendableCallable() { 144 | 145 | @Override 146 | public String run() throws SuspendExecution, InterruptedException { 147 | try { 148 | return ChannelObservable.get(o); 149 | } catch (ExecutionException e) { 150 | throw new AssertionError(); 151 | } 152 | } 153 | }).start(); 154 | 155 | Thread.sleep(100); 156 | 157 | o.onNext("foo"); 158 | o.onCompleted(); 159 | 160 | assertThat(f.get(), equalTo("foo")); 161 | } 162 | 163 | @Test 164 | public void whenGetAndObservableFailsThenThrowExecutionException() throws Exception { 165 | final PublishSubject o = PublishSubject.create(); 166 | 167 | Fiber f = new Fiber(new SuspendableCallable() { 168 | 169 | @Override 170 | public String run() throws SuspendExecution, InterruptedException { 171 | try { 172 | return ChannelObservable.get(o); 173 | } catch (ExecutionException e) { 174 | return e.getCause().getMessage(); 175 | } 176 | } 177 | }).start(); 178 | 179 | Thread.sleep(100); 180 | 181 | o.onError(new Exception("ohoh")); 182 | 183 | assertThat(f.get(), equalTo("ohoh")); 184 | } 185 | 186 | @Test 187 | public void whenGetAndObservableEmitsTwoValuesThenBlowup() throws Exception { 188 | final PublishSubject o = PublishSubject.create(); 189 | 190 | new Fiber(new SuspendableCallable() { 191 | 192 | @Override 193 | public String run() throws SuspendExecution, InterruptedException { 194 | try { 195 | return ChannelObservable.get(o); 196 | } catch (ExecutionException e) { 197 | throw new AssertionError(); 198 | } 199 | } 200 | }).start(); 201 | 202 | Thread.sleep(100); 203 | 204 | o.onNext("foo"); 205 | try { 206 | o.onNext("bar"); 207 | fail(); 208 | } catch (Exception e) { 209 | } 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/NewFiberSchedulerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | import rx.Scheduler; 19 | 20 | public class NewFiberSchedulerTest extends AbstractSchedulerConcurrencyTests { 21 | // @Rule 22 | // public TestRule globalTimeout = new Timeout(20000); 23 | 24 | @Override 25 | protected Scheduler getScheduler() { 26 | return NewFiberScheduler.getDefaultInstance(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/rx/quasar/TestException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package rx.quasar; 17 | 18 | /** 19 | * Custom exception for operator testing; makes sure an unwanted exception is 20 | * not mixed up with a wanted exception. 21 | */ 22 | public final class TestException extends RuntimeException { 23 | /** */ 24 | private static final long serialVersionUID = -1138830497957801910L; 25 | /** Create the test exception without any message. */ 26 | public TestException() { 27 | super(); 28 | } 29 | /** 30 | * Create the test exception with the provided message. 31 | * @param message the mesage to use 32 | */ 33 | public TestException(String message) { 34 | super(message); 35 | } 36 | } 37 | --------------------------------------------------------------------------------