├── .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 extends T> o;
63 |
64 | private BlockingObservable(Observable extends T> o) {
65 | this.o = o;
66 | }
67 |
68 | /**
69 | * Convert an Observable into a BlockingObservable.
70 | */
71 | public static BlockingObservable from(final Observable extends T> 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 super T> 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 super T> 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 super T, Boolean> 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 super T, Boolean> 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 super T, Boolean> 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 super T, Boolean> 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 super T, Boolean> 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 extends T> 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 super T, Boolean> 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 | *
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 extends T> 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 | *
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 | *
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 | *
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 | *