Repository: ReactiveX/RxAndroid Branch: 3.x Commit: d7bd9b74f405 Files: 40 Total size: 98.9 KB Directory structure: gitextract_5o4pvf00/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── dependabot.yaml │ └── workflows/ │ ├── build.yaml │ ├── manual_drop.yaml │ └── release.yaml ├── .gitignore ├── CHANGES.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── rxandroid/ │ ├── build.gradle │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── io/ │ │ └── reactivex/ │ │ └── rxjava3/ │ │ └── android/ │ │ ├── MainThreadDisposable.java │ │ ├── plugins/ │ │ │ └── RxAndroidPlugins.java │ │ └── schedulers/ │ │ ├── AndroidSchedulers.java │ │ └── HandlerScheduler.java │ └── test/ │ └── java/ │ └── io/ │ └── reactivex/ │ └── rxjava3/ │ └── android/ │ ├── MainThreadDisposableTest.java │ ├── plugins/ │ │ ├── RxAndroidPluginsNoRobolectricTest.java │ │ └── RxAndroidPluginsTest.java │ ├── schedulers/ │ │ ├── AndroidSchedulersTest.java │ │ └── HandlerSchedulerTest.java │ └── testutil/ │ ├── CountingRunnable.java │ └── EmptyScheduler.java ├── sample-app/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── io/ │ │ └── reactivex/ │ │ └── rxjava3/ │ │ └── android/ │ │ └── samples/ │ │ └── MainActivity.java │ └── res/ │ ├── layout/ │ │ └── main_activity.xml │ ├── values/ │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── values-w820dp/ │ └── dimens.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [{*.yml,*.yaml}] indent_size = 2 ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf *.bat text eol=crlf *.jar binary ================================================ FILE: .github/dependabot.yaml ================================================ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" ================================================ FILE: .github/workflows/build.yaml ================================================ name: build on: pull_request: {} push: branches: - '**' tags-ignore: - '**' jobs: build: runs-on: macos-latest steps: - uses: actions/checkout@v6 - uses: gradle/actions/wrapper-validation@v5 - uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: 8 - run: ./gradlew build - run: ./gradlew publish if: ${{ github.ref == 'refs/heads/3.x' && github.repository == 'ReactiveX/RxAndroid' }} env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USER }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }} ================================================ FILE: .github/workflows/manual_drop.yaml ================================================ name: 'Sonatype: manual close+release' on: workflow_dispatch: inputs: repository_name: description: 'Name of staged repository on Sonatype' type: string jobs: close_and_release: runs-on: macos-latest steps: - uses: actions/checkout@v6 - uses: gradle/actions/wrapper-validation@v5 - uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: 8 - run: ./gradlew closeAndReleaseRepository --repository=${{ inputs.repository_name }} env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USER }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }} ================================================ FILE: .github/workflows/release.yaml ================================================ name: release on: push: tags: - '**' jobs: release: runs-on: macos-latest steps: - uses: actions/checkout@v6 - uses: gradle/actions/wrapper-validation@v5 - uses: actions/setup-java@v5 with: distribution: 'zulu' java-version: 8 - run: ./gradlew publish env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USER }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }} ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_PRIVATE_KEY }} ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} - run: ./gradlew closeAndReleaseRepository env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USER }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }} ================================================ FILE: .gitignore ================================================ # Gradle .gradle build reports # IntelliJ .idea # Android local.properties ================================================ FILE: CHANGES.md ================================================ # RxAndroid Releases # ### Version 3.0.2 - November, 9 2022 ### Fixed: - Ensure the main scheduler can be replaced in unit tests without needing Robolectric. ### Version 3.0.1 - November, 8 2022 ### Fixed: - `AndroidSchedulers.mainThread()` now correctly checks whether async messages are supported by the current Android version. Previously it always assumed they were available (true on API 16+). Changed: - Update to RxJava 3.1.5. This includes a transitive dependency bump to Reactive-Streams 1.0.4 which re-licenses that dependency from CC-0 to MIT-0. ### Version 3.0.0 - February, 14 2020 ### General availability of RxAndroid 3.0 for use with RxJava 3.0! The Maven groupId has changed to `io.reactivex.rxjava3` and the package is now `io.reactivex.rxjava3.android`. The APIs and behavior of RxAndroid 3.0.0 is otherwise exactly the same as RxAndroid 2.1.1 with one notable exception: Schedulers created via `AndroidSchedulers.from` now deliver [async messages](https://developer.android.com/reference/android/os/Handler.html#createAsync(android.os.Looper)) by default. This is also true for `AndroidSchedulers.mainThread()`. For more information about RxJava 3.0 see [its release notes](https://github.com/ReactiveX/RxJava/releases/tag/v3.0.0). --- Version 2.x can be found at https://github.com/ReactiveX/RxAndroid/blob/2.x/CHANGES.md Version 1.x can be found at https://github.com/ReactiveX/RxAndroid/blob/1.x/CHANGES.md ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to RxJava 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`). When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. ## License By contributing your code, you agree to license your contribution under the terms of the APLv2: https://github.com/ReactiveX/RxAndroid/blob/2.x/LICENSE All files are released with the Apache 2.0 license. If you are adding a new file it should have a header like this: ``` /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # RxAndroid: Reactive Extensions for Android Android specific bindings for [RxJava 3](http://github.com/ReactiveX/RxJava). This module adds the minimum classes to RxJava that make writing reactive components in Android applications easy and hassle-free. More specifically, it provides a `Scheduler` that schedules on the main thread or any given `Looper`. ## Communication Since RxAndroid is part of the RxJava family the communication channels are similar: - Google Group: [RxJava][list] - Twitter: [@RxJava][twitter] - StackOverflow: [rx-android][so] - [GitHub Issues][issues] # Binaries ```groovy dependencies { implementation 'io.reactivex.rxjava3:rxandroid:3.0.2' // Because RxAndroid releases are few and far between, it is recommended you also // explicitly depend on RxJava's latest version for bug fixes and new features. // (see https://github.com/ReactiveX/RxJava/releases for latest 3.x.x version) implementation 'io.reactivex.rxjava3:rxjava:3.1.5' } ``` * RxAndroid: * RxJava: Additional binaries and dependency information for can be found at [search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.reactivex.rxjava3%22%20a%3A%22rxandroid%22).
Snapshots of the development version are available in Sonatype's snapshots repository.

```groovy repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { implementation 'io.reactivex.rxjava3:rxandroid:3.1.0-SNAPSHOT' } ```

## Build To build: ```bash $ git clone git@github.com:ReactiveX/RxAndroid.git $ cd RxAndroid/ $ ./gradlew build ``` Further details on building can be found on the RxJava [Getting Started][start] page of the wiki. # Sample usage A sample project which provides runnable code examples that demonstrate uses of the classes in this project is available in the `sample-app/` folder. ## Observing on the main thread One of the most common operations when dealing with asynchronous tasks on Android is to observe the task's result or outcome on the main thread. Using vanilla Android, this would typically be accomplished with an `AsyncTask`. With RxJava instead you would declare your `Observable` to be observed on the main thread: ```java Observable.just("one", "two", "three", "four", "five") .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(/* an Observer */); ``` This will execute the `Observable` on a new thread, and emit results through `onNext` on the main thread. ## Observing on arbitrary loopers The previous sample is merely a specialization of a more general concept: binding asynchronous communication to an Android message loop, or `Looper`. In order to observe an `Observable` on an arbitrary `Looper`, create an associated `Scheduler` by calling `AndroidSchedulers.from`: ```java Looper backgroundLooper = // ... Observable.just("one", "two", "three", "four", "five") .observeOn(AndroidSchedulers.from(backgroundLooper)) .subscribe(/* an Observer */) ``` This will execute the Observable on a new thread and emit results through `onNext` on whatever thread is running `backgroundLooper`. ## Bugs and Feedback For bugs, feature requests, and discussion please use [GitHub Issues][issues]. For general usage questions please use the [mailing list][list] or [StackOverflow][so]. ## LICENSE Copyright 2015 The RxAndroid authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. [list]: http://groups.google.com/d/forum/rxjava [so]: http://stackoverflow.com/questions/tagged/rx-android [twitter]: http://twitter.com/RxJava [issues]: https://github.com/ReactiveX/RxAndroid/issues [start]: https://github.com/ReactiveX/RxJava/wiki/Getting-Started ================================================ FILE: RELEASING.md ================================================ Release Process =============== 1. Ensure `VERSION_NAME` in `gradle.properties` is set to the version you want to release. 2. Add an entry in `CHANGELOG.md` with the changes for the release. 3. Update `README.md` with the version about to be released. Also update the RxJava version in this file to its latest. 4. Update the RxJava version in `rxandroid/build.gradle` to its latest. (We tell people that we won't be tracking RxJava releases, and we don't, but we do it anyway when we are releasing for those who ignore the advice.) 5. Commit: `git commit -am "Prepare version X.Y.X"` 6. Tag: `git tag -a X.Y.Z -m "Version X.Y.Z"` 7. Update `VERSION_NAME` in `gradle.properties` to the next development version. You MUST include `-SNAPSHOT` on the new version. 8. Commit: `git commit -am "Prepare next development version."` 9. Push: `git push && git push --tags` 10. Paste the `CHANGELOG.md` contents for this version into a Release on GitHub along with the Groovy for depending on the new version (https://github.com/ReactiveX/RxAndroid/releases). ================================================ FILE: build.gradle ================================================ buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.2.2' classpath 'com.vanniktech:gradle-maven-publish-plugin:0.18.0' } } allprojects { repositories { google() mavenCentral() } tasks.withType(Test).configureEach { testLogging { if (System.getenv("CI") == "true") { events = ["failed", "skipped", "passed"] } exceptionFormat "full" } } } ext { minSdkVersion = 9 compileSdkVersion = 31 sourceCompatibility = JavaVersion.VERSION_1_8 } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ org.gradle.jvmargs=-Xmx2048m android.useAndroidX=true android.enableJetifier=false android.defaults.buildfeatures.buildconfig=false android.defaults.buildfeatures.aidl=false android.defaults.buildfeatures.renderscript=false android.defaults.buildfeatures.resvalues=false android.defaults.buildfeatures.shaders=false GROUP=io.reactivex.rxjava3 VERSION_NAME=3.1.0-SNAPSHOT POM_NAME=RxAndroid POM_DESCRIPTION=RxAndroid POM_URL=https://github.com/ReactiveX/RxAndroid POM_SCM_URL=https://github.com/ReactiveX/RxAndroid POM_SCM_CONNECTION=scm:git:https://github.com/ReactiveX/RxAndroid.git POM_SCM_DEV_CONNECTION=scm:git:git@github.com:ReactiveX/RxAndroid.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=reactivex POM_DEVELOPER_NAME=ReactiveX POM_DEVELOPER_URL=https://github.com/ReactiveX ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: rxandroid/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.vanniktech.maven.publish' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } compileOptions { sourceCompatibility rootProject.ext.sourceCompatibility targetCompatibility rootProject.ext.sourceCompatibility } testOptions { unitTests.returnDefaultValues = true } } dependencies { api 'io.reactivex.rxjava3:rxjava:3.1.5' testImplementation 'junit:junit:4.13.2' testImplementation 'org.robolectric:robolectric:4.2.1' } signing { def signingKey = findProperty('signingKey') def signingPassword = findProperty('signingPassword') useInMemoryPgpKeys(signingKey, signingPassword) } ================================================ FILE: rxandroid/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxandroid/src/main/java/io/reactivex/rxjava3/android/MainThreadDisposable.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android; import android.os.Looper; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.disposables.Disposable; import java.util.concurrent.atomic.AtomicBoolean; /** * A {@linkplain Disposable disposable} which ensures its {@linkplain #onDispose() * dispose action} is executed on the main thread. When unsubscription occurs on a different * thread than the main thread, the action is posted to run on the main thread as soon as possible. *

* Instances of this class are useful in creating observables which interact with APIs that can * only be used on the main thread, such as UI objects. *

* A {@link #verifyMainThread() convenience method} is also provided for validating whether code * is being called on the main thread. Calls to this method along with instances of this class are * commonly used when creating custom observables using the following pattern: *


 * @Override public void subscribe(Observer o) {
 *   MainThreadDisposable.verifyMainThread();
 *
 *   // TODO setup behavior
 *
 *    o.onSubscribe(new MainThreadDisposable() {
 *     @Override protected void onDispose() {
 *       // TODO undo behavior
 *     }
 *   });
 * }
 * 
*/ public abstract class MainThreadDisposable implements Disposable { /** * Verify that the calling thread is the Android main thread. *

* Calls to this method are usually preconditions for subscription behavior which instances of * this class later undo. See the class documentation for an example. * * @throws IllegalStateException when called from any other thread. */ public static void verifyMainThread() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalStateException( "Expected to be called on the main thread but was " + Thread.currentThread().getName()); } } private final AtomicBoolean unsubscribed = new AtomicBoolean(); @Override public final boolean isDisposed() { return unsubscribed.get(); } @Override public final void dispose() { if (unsubscribed.compareAndSet(false, true)) { if (Looper.myLooper() == Looper.getMainLooper()) { onDispose(); } else { AndroidSchedulers.mainThread().scheduleDirect(this::onDispose); } } } protected abstract void onDispose(); } ================================================ FILE: rxandroid/src/main/java/io/reactivex/rxjava3/android/plugins/RxAndroidPlugins.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.plugins; import java.util.concurrent.Callable; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.exceptions.Exceptions; import io.reactivex.rxjava3.functions.Function; /** * Utility class to inject handlers to certain standard RxAndroid operations. */ public final class RxAndroidPlugins { private static volatile Function, Scheduler> onInitMainThreadHandler; private static volatile Function onMainThreadHandler; public static void setInitMainThreadSchedulerHandler(Function, Scheduler> handler) { onInitMainThreadHandler = handler; } public static Scheduler initMainThreadScheduler(Callable scheduler) { if (scheduler == null) { throw new NullPointerException("scheduler == null"); } Function, Scheduler> f = onInitMainThreadHandler; if (f == null) { return callRequireNonNull(scheduler); } return applyRequireNonNull(f, scheduler); } public static void setMainThreadSchedulerHandler(Function handler) { onMainThreadHandler = handler; } public static Scheduler onMainThreadScheduler(Scheduler scheduler) { if (scheduler == null) { throw new NullPointerException("scheduler == null"); } Function f = onMainThreadHandler; if (f == null) { return scheduler; } return apply(f, scheduler); } /** * Returns the current hook function. * @return the hook function, may be null */ public static Function, Scheduler> getInitMainThreadSchedulerHandler() { return onInitMainThreadHandler; } /** * Returns the current hook function. * @return the hook function, may be null */ public static Function getOnMainThreadSchedulerHandler() { return onMainThreadHandler; } /** * Removes all handlers and resets the default behavior. */ public static void reset() { setInitMainThreadSchedulerHandler(null); setMainThreadSchedulerHandler(null); } static Scheduler callRequireNonNull(Callable s) { try { Scheduler scheduler = s.call(); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; } catch (Throwable ex) { throw Exceptions.propagate(ex); } } static Scheduler applyRequireNonNull(Function, Scheduler> f, Callable s) { Scheduler scheduler = apply(f,s); if (scheduler == null) { throw new NullPointerException("Scheduler Callable returned null"); } return scheduler; } static R apply(Function f, T t) { try { return f.apply(t); } catch (Throwable ex) { throw Exceptions.propagate(ex); } } private RxAndroidPlugins() { throw new AssertionError("No instances."); } } ================================================ FILE: rxandroid/src/main/java/io/reactivex/rxjava3/android/schedulers/AndroidSchedulers.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.schedulers; import android.annotation.SuppressLint; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins; import io.reactivex.rxjava3.core.Scheduler; /** Android-specific Schedulers. */ public final class AndroidSchedulers { private static final class MainHolder { static final Scheduler DEFAULT = internalFrom(Looper.getMainLooper(), true); } private static final Scheduler MAIN_THREAD = RxAndroidPlugins.initMainThreadScheduler(() -> MainHolder.DEFAULT); /** * A {@link Scheduler} which executes actions on the Android main thread. *

* The returned scheduler will post asynchronous messages to the looper by default. * * @see #from(Looper, boolean) */ public static Scheduler mainThread() { return RxAndroidPlugins.onMainThreadScheduler(MAIN_THREAD); } /** * A {@link Scheduler} which executes actions on {@code looper}. *

* The returned scheduler will post asynchronous messages to the looper by default. * * @see #from(Looper, boolean) */ public static Scheduler from(Looper looper) { return from(looper, true); } /** * A {@link Scheduler} which executes actions on {@code looper}. * * @param async if true, the scheduler will use async messaging on API >= 16 to avoid VSYNC * locking. On API < 16 this value is ignored. * @see Message#setAsynchronous(boolean) */ public static Scheduler from(Looper looper, boolean async) { if (looper == null) throw new NullPointerException("looper == null"); return internalFrom(looper, async); } @SuppressLint("NewApi") // Checking for an @hide API. private static Scheduler internalFrom(Looper looper, boolean async) { // Below code exists in androidx-core as well, but is left here rather than include an // entire extra dependency. // https://developer.android.com/reference/kotlin/androidx/core/os/MessageCompat?hl=en#setAsynchronous(android.os.Message,%20kotlin.Boolean) if (Build.VERSION.SDK_INT < 16) { async = false; } else if (async && Build.VERSION.SDK_INT < 22) { // Confirm that the method is available on this API level despite being @hide. Message message = Message.obtain(); try { message.setAsynchronous(true); } catch (NoSuchMethodError e) { async = false; } message.recycle(); } return new HandlerScheduler(new Handler(looper), async); } private AndroidSchedulers() { throw new AssertionError("No instances."); } } ================================================ FILE: rxandroid/src/main/java/io/reactivex/rxjava3/android/schedulers/HandlerScheduler.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.schedulers; import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import java.util.concurrent.TimeUnit; final class HandlerScheduler extends Scheduler { private final Handler handler; private final boolean async; HandlerScheduler(Handler handler, boolean async) { this.handler = handler; this.async = async; } @Override @SuppressLint("NewApi") // Async will only be true when the API is available to call. public Disposable scheduleDirect(Runnable run, long delay, TimeUnit unit) { if (run == null) throw new NullPointerException("run == null"); if (unit == null) throw new NullPointerException("unit == null"); run = RxJavaPlugins.onSchedule(run); ScheduledRunnable scheduled = new ScheduledRunnable(handler, run); Message message = Message.obtain(handler, scheduled); if (async) { message.setAsynchronous(true); } handler.sendMessageDelayed(message, unit.toMillis(delay)); return scheduled; } @Override public Worker createWorker() { return new HandlerWorker(handler, async); } private static final class HandlerWorker extends Worker { private final Handler handler; private final boolean async; private volatile boolean disposed; HandlerWorker(Handler handler, boolean async) { this.handler = handler; this.async = async; } @Override @SuppressLint("NewApi") // Async will only be true when the API is available to call. public Disposable schedule(Runnable run, long delay, TimeUnit unit) { if (run == null) throw new NullPointerException("run == null"); if (unit == null) throw new NullPointerException("unit == null"); if (disposed) { return Disposable.disposed(); } run = RxJavaPlugins.onSchedule(run); ScheduledRunnable scheduled = new ScheduledRunnable(handler, run); Message message = Message.obtain(handler, scheduled); message.obj = this; // Used as token for batch disposal of this worker's runnables. if (async) { message.setAsynchronous(true); } handler.sendMessageDelayed(message, unit.toMillis(delay)); // Re-check disposed state for removing in case we were racing a call to dispose(). if (disposed) { handler.removeCallbacks(scheduled); return Disposable.disposed(); } return scheduled; } @Override public void dispose() { disposed = true; handler.removeCallbacksAndMessages(this /* token */); } @Override public boolean isDisposed() { return disposed; } } private static final class ScheduledRunnable implements Runnable, Disposable { private final Handler handler; private final Runnable delegate; private volatile boolean disposed; // Tracked solely for isDisposed(). ScheduledRunnable(Handler handler, Runnable delegate) { this.handler = handler; this.delegate = delegate; } @Override public void run() { try { delegate.run(); } catch (Throwable t) { RxJavaPlugins.onError(t); } } @Override public void dispose() { handler.removeCallbacks(this); disposed = true; } @Override public boolean isDisposed() { return disposed; } } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/MainThreadDisposableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android; import io.reactivex.rxjava3.disposables.Disposable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLooper; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(RobolectricTestRunner.class) @Config(manifest=Config.NONE) public final class MainThreadDisposableTest { @Test public void verifyDoesNotThrowOnMainThread() throws InterruptedException { MainThreadDisposable.verifyMainThread(); // Robolectric tests run on its main thread. } @Test public void verifyThrowsOffMainThread() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { try { MainThreadDisposable.verifyMainThread(); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().startsWith("Expected to be called on the main thread")); latch.countDown(); } } }).start(); assertTrue(latch.await(1, SECONDS)); } @Test public void onUnsubscribeRunsSyncOnMainThread() { ShadowLooper.pauseMainLooper(); final AtomicBoolean called = new AtomicBoolean(); new MainThreadDisposable() { @Override protected void onDispose() { called.set(true); } }.dispose(); assertTrue(called.get()); } @Test public void unsubscribeTwiceDoesNotRunTwice() { final AtomicInteger called = new AtomicInteger(0); Disposable disposable = new MainThreadDisposable() { @Override protected void onDispose() { called.incrementAndGet(); } }; disposable.dispose(); disposable.dispose(); disposable.dispose(); assertEquals(1, called.get()); } @Test public void onUnsubscribePostsOffMainThread() throws InterruptedException { ShadowLooper.pauseMainLooper(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean called = new AtomicBoolean(); new Thread(new Runnable() { @Override public void run() { new MainThreadDisposable() { @Override protected void onDispose() { called.set(true); } }.dispose(); latch.countDown(); } }).start(); assertTrue(latch.await(1, SECONDS)); assertFalse(called.get()); // Callback has not yet run. ShadowLooper.runMainLooperOneTask(); assertTrue(called.get()); } @Test public void disposedState() { MainThreadDisposable disposable = new MainThreadDisposable() { @Override protected void onDispose() { } }; assertFalse(disposable.isDisposed()); disposable.dispose(); assertTrue(disposable.isDisposed()); } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/plugins/RxAndroidPluginsNoRobolectricTest.java ================================================ package io.reactivex.rxjava3.android.plugins; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.android.testutil.EmptyScheduler; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertSame; public final class RxAndroidPluginsNoRobolectricTest { @Before @After public void setUpAndTearDown() { RxAndroidPlugins.reset(); } @Test public void mainThreadSchedulerCanBeReplaced() { EmptyScheduler emptyScheduler = new EmptyScheduler(); RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler -> emptyScheduler); assertSame(emptyScheduler, AndroidSchedulers.mainThread()); } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/plugins/RxAndroidPluginsTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.plugins; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; import io.reactivex.rxjava3.android.testutil.EmptyScheduler; import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.schedulers.Schedulers; import static junit.framework.TestCase.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @RunWith(RobolectricTestRunner.class) @Config(manifest=Config.NONE) public final class RxAndroidPluginsTest { @Before @After public void setUpAndTearDown() { RxAndroidPlugins.reset(); } @Test public void mainThreadHandlerCalled() { final AtomicReference schedulerRef = new AtomicReference<>(); final Scheduler newScheduler = new EmptyScheduler(); RxAndroidPlugins.setMainThreadSchedulerHandler(new Function() { @Override public Scheduler apply(Scheduler scheduler) { schedulerRef.set(scheduler); return newScheduler; } }); Scheduler scheduler = new EmptyScheduler(); Scheduler actual = RxAndroidPlugins.onMainThreadScheduler(scheduler); assertSame(newScheduler, actual); assertSame(scheduler, schedulerRef.get()); } @Test public void resetClearsMainThreadHandler() { RxAndroidPlugins.setMainThreadSchedulerHandler(new Function() { @Override public Scheduler apply(Scheduler scheduler) { throw new AssertionError(); } }); RxAndroidPlugins.reset(); Scheduler scheduler = new EmptyScheduler(); Scheduler actual = RxAndroidPlugins.onMainThreadScheduler(scheduler); assertSame(scheduler, actual); } @Test public void initMainThreadHandlerCalled() { final AtomicReference> schedulerRef = new AtomicReference<>(); final Scheduler newScheduler = new EmptyScheduler(); RxAndroidPlugins .setInitMainThreadSchedulerHandler(new Function, Scheduler>() { @Override public Scheduler apply(Callable scheduler) { schedulerRef.set(scheduler); return newScheduler; } }); Callable scheduler = new Callable() { @Override public Scheduler call() throws Exception { throw new AssertionError(); } }; Scheduler actual = RxAndroidPlugins.initMainThreadScheduler(scheduler); assertSame(newScheduler, actual); assertSame(scheduler, schedulerRef.get()); } @Test public void resetClearsInitMainThreadHandler() throws Exception { RxAndroidPlugins .setInitMainThreadSchedulerHandler(new Function, Scheduler>() { @Override public Scheduler apply(Callable scheduler) { throw new AssertionError(); } }); final Scheduler scheduler = new EmptyScheduler(); Callable schedulerCallable = new Callable() { @Override public Scheduler call() throws Exception { return scheduler; } }; RxAndroidPlugins.reset(); Scheduler actual = RxAndroidPlugins.initMainThreadScheduler(schedulerCallable); assertSame(schedulerCallable.call(), actual); } @Test public void defaultMainThreadSchedulerIsInitializedLazily() { Function, Scheduler> safeOverride = new Function, Scheduler>() { @Override public Scheduler apply(Callable scheduler) { return new EmptyScheduler(); } }; Callable unsafeDefault = new Callable() { @Override public Scheduler call() throws Exception { throw new AssertionError(); } }; RxAndroidPlugins.setInitMainThreadSchedulerHandler(safeOverride); RxAndroidPlugins.initMainThreadScheduler(unsafeDefault); } @Test public void overrideInitMainSchedulerThrowsWhenSchedulerCallableIsNull() { try { RxAndroidPlugins.initMainThreadScheduler(null); fail(); } catch (NullPointerException e) { assertEquals("scheduler == null", e.getMessage()); } } @Test public void overrideInitMainSchedulerThrowsWhenSchedulerCallableReturnsNull() { Callable nullResultCallable = new Callable() { @Override public Scheduler call() throws Exception { return null; } }; try { RxAndroidPlugins.initMainThreadScheduler(nullResultCallable); fail(); } catch (NullPointerException e) { assertEquals("Scheduler Callable returned null", e.getMessage()); } } @Test public void getInitMainThreadSchedulerHandlerReturnsHandler() { Function, Scheduler> handler = new Function, Scheduler>() { @Override public Scheduler apply(Callable schedulerCallable) throws Exception { return Schedulers.trampoline(); } }; RxAndroidPlugins.setInitMainThreadSchedulerHandler(handler); assertSame(handler, RxAndroidPlugins.getInitMainThreadSchedulerHandler()); } @Test public void getMainThreadSchedulerHandlerReturnsHandler() { Function handler = new Function() { @Override public Scheduler apply(Scheduler scheduler) { return Schedulers.trampoline(); } }; RxAndroidPlugins.setMainThreadSchedulerHandler(handler); assertSame(handler, RxAndroidPlugins.getOnMainThreadSchedulerHandler()); } @Test public void getInitMainThreadSchedulerHandlerReturnsNullIfNotSet() { RxAndroidPlugins.reset(); assertNull(RxAndroidPlugins.getInitMainThreadSchedulerHandler()); } @Test public void getMainThreadSchedulerHandlerReturnsNullIfNotSet() { RxAndroidPlugins.reset(); assertNull(RxAndroidPlugins.getOnMainThreadSchedulerHandler()); } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/schedulers/AndroidSchedulersTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.schedulers; import android.os.Build; import android.os.Looper; import android.os.Message; import io.reactivex.rxjava3.android.plugins.RxAndroidPlugins; import io.reactivex.rxjava3.android.testutil.EmptyScheduler; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.functions.Function; import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLooper; import org.robolectric.shadows.ShadowMessageQueue; import org.robolectric.util.ReflectionHelpers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.robolectric.Shadows.shadowOf; @RunWith(RobolectricTestRunner.class) @Config(manifest=Config.NONE) public final class AndroidSchedulersTest { @Before @After public void setUpAndTearDown() { RxAndroidPlugins.reset(); } @Test public void mainThreadCallsThroughToHook() { final AtomicInteger called = new AtomicInteger(); final Scheduler newScheduler = new EmptyScheduler(); RxAndroidPlugins.setMainThreadSchedulerHandler(new Function() { @Override public Scheduler apply(Scheduler scheduler) { called.getAndIncrement(); return newScheduler; } }); assertSame(newScheduler, AndroidSchedulers.mainThread()); assertEquals(1, called.get()); assertSame(newScheduler, AndroidSchedulers.mainThread()); assertEquals(2, called.get()); } @Test public void fromNullThrows() { try { AndroidSchedulers.from(null); fail(); } catch (NullPointerException e) { assertEquals("looper == null", e.getMessage()); } } @Test public void fromNullThrowsTwoArg() { try { AndroidSchedulers.from(null, false); fail(); } catch (NullPointerException e) { assertEquals("looper == null", e.getMessage()); } } @Test public void fromReturnsUsableScheduler() { assertNotNull(AndroidSchedulers.from(Looper.getMainLooper())); } @Test public void mainThreadAsyncMessagesByDefault() { ShadowLooper mainLooper = shadowOf(Looper.getMainLooper()); mainLooper.pause(); ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); Scheduler main = AndroidSchedulers.mainThread(); main.scheduleDirect(new Runnable() { @Override public void run() { } }); Message message = mainMessageQueue.getHead(); assertTrue(message.isAsynchronous()); } @Test public void fromAsyncMessagesByDefault() { ShadowLooper mainLooper = shadowOf(Looper.getMainLooper()); mainLooper.pause(); ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); Scheduler main = AndroidSchedulers.from(Looper.getMainLooper()); main.scheduleDirect(new Runnable() { @Override public void run() { } }); Message message = mainMessageQueue.getHead(); assertTrue(message.isAsynchronous()); } @Test public void asyncIgnoredPre16() { int oldValue = Build.VERSION.SDK_INT; ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 14); try { ShadowLooper mainLooper = shadowOf(Looper.getMainLooper()); mainLooper.pause(); ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); Scheduler main = AndroidSchedulers.from(Looper.getMainLooper(), true); main.scheduleDirect(new Runnable() { @Override public void run() { } }); Message message = mainMessageQueue.getHead(); assertFalse(message.isAsynchronous()); } finally { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", oldValue); } } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/schedulers/HandlerSchedulerTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.schedulers; import android.os.Handler; import android.os.Looper; import android.os.Message; import io.reactivex.rxjava3.android.testutil.CountingRunnable; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.core.Scheduler.Worker; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.functions.Consumer; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.ParameterizedRobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLooper; import org.robolectric.shadows.ShadowMessageQueue; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.robolectric.Shadows.shadowOf; import static org.robolectric.shadows.ShadowLooper.idleMainLooper; import static org.robolectric.shadows.ShadowLooper.pauseMainLooper; import static org.robolectric.shadows.ShadowLooper.runUiThreadTasks; import static org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks; import static org.robolectric.shadows.ShadowLooper.unPauseMainLooper; @RunWith(ParameterizedRobolectricTestRunner.class) @Config(manifest=Config.NONE, sdk = 16) public final class HandlerSchedulerTest { @ParameterizedRobolectricTestRunner.Parameters(name = "async = {0}") public static Collection data() { return Arrays.asList(new Object[][]{ {true}, {false} }); } private final Scheduler scheduler; private final boolean async; public HandlerSchedulerTest(boolean async) { this.scheduler = new HandlerScheduler(new Handler(Looper.getMainLooper()), async); this.async = async; } @Before public void setUp() { RxJavaPlugins.reset(); pauseMainLooper(); // Take manual control of looper task queue. } @After public void tearDown() { RxJavaPlugins.reset(); unPauseMainLooper(); } @Test public void directScheduleOncePostsImmediately() { CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void directScheduleOnceWithNegativeDelayPostsImmediately() { CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter, -1, TimeUnit.MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void directScheduleOnceUsesHook() { final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter); // Verify our runnable was passed to the schedulers hook. assertSame(counter, runnableRef.get()); runUiThreadTasks(); // Verify the scheduled runnable was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); } @Test public void directScheduleOnceDisposedDoesNotRun() { CountingRunnable counter = new CountingRunnable(); Disposable disposable = scheduler.scheduleDirect(counter); disposable.dispose(); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test public void directScheduleOnceWithDelayPostsWithDelay() { CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void directScheduleOnceWithDelayUsesHook() { final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); CountingRunnable counter = new CountingRunnable(); scheduler.scheduleDirect(counter, 1, MINUTES); // Verify our runnable was passed to the schedulers hook. assertSame(counter, runnableRef.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); // Verify the scheduled runnable was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); } @Test public void directScheduleOnceWithDelayDisposedDoesNotRun() { CountingRunnable counter = new CountingRunnable(); Disposable disposable = scheduler.scheduleDirect(counter, 1, MINUTES); idleMainLooper(30, SECONDS); disposable.dispose(); idleMainLooper(30, SECONDS); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyReschedulesItself() { CountingRunnable counter = new CountingRunnable(); scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(3, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyUsesHookOnce() { final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); CountingRunnable counter = new CountingRunnable(); scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES); // Verify our action was passed to the schedulers hook. assertSame(counter, runnableRef.get()); runnableRef.set(null); idleMainLooper(1, MINUTES); runUiThreadTasks(); // Verify the scheduled action was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); // Ensure the hook was not called again when the runnable re-scheduled itself. assertNull(runnableRef.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyDisposedDoesNotRun() { CountingRunnable counter = new CountingRunnable(); Disposable disposable = scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); disposable.dispose(); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyDisposedDuringRunDoesNotReschedule() { final AtomicReference disposableRef = new AtomicReference<>(); CountingRunnable counter = new CountingRunnable() { @Override public void run() { super.run(); if (get() == 2) { disposableRef.get().dispose(); } } }; Disposable disposable = scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES); disposableRef.set(disposable); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); // Dispose will have happened here during the last run() execution. idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyThrowingDoesNotReschedule() { CountingRunnable counter = new CountingRunnable() { @Override public void run() { super.run(); if (get() == 2) { throw new RuntimeException("Broken!"); } } }; scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); // Exception will have happened here during the last run() execution. idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test public void workerScheduleOncePostsImmediately() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void workerScheduleOnceWithNegativeDelayPostsImmediately() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter, -1, TimeUnit.MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void workerScheduleOnceUsesHook() { final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter); // Verify our runnable was passed to the schedulers hook. assertSame(counter, runnableRef.get()); runUiThreadTasks(); // Verify the scheduled runnable was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); } @Test public void workerScheduleOnceDisposedDoesNotRun() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); Disposable disposable = worker.schedule(counter); disposable.dispose(); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test public void workerScheduleOnceWithDelayPostsWithDelay() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); } @Test public void workerScheduleOnceWithDelayUsesHook() { final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter, 1, MINUTES); // Verify our runnable was passed to the schedulers hook. assertSame(counter, runnableRef.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); // Verify the scheduled runnable was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); } @Test public void workerScheduleOnceWithDelayDisposedDoesNotRun() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); Disposable disposable = worker.schedule(counter, 1, MINUTES); idleMainLooper(30, SECONDS); disposable.dispose(); idleMainLooper(30, SECONDS); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyReschedulesItself() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedulePeriodically(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(3, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyUsesHookOnce() { Worker worker = scheduler.createWorker(); final CountingRunnable newCounter = new CountingRunnable(); final AtomicReference runnableRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { runnableRef.set(runnable); return newCounter; } }); CountingRunnable counter = new CountingRunnable(); worker.schedulePeriodically(counter, 1, 1, MINUTES); // Verify our action was passed to the schedulers hook. assertSame(counter, runnableRef.get()); runnableRef.set(null); idleMainLooper(1, MINUTES); runUiThreadTasks(); // Verify the scheduled action was the one returned from the hook. assertEquals(1, newCounter.get()); assertEquals(0, counter.get()); // Ensure the hook was not called again when the runnable re-scheduled itself. assertNull(runnableRef.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyDisposedDoesNotRun() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); Disposable disposable = worker.schedulePeriodically(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); disposable.dispose(); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyDisposedDuringRunDoesNotReschedule() { Worker worker = scheduler.createWorker(); final AtomicReference disposableRef = new AtomicReference<>(); CountingRunnable counter = new CountingRunnable() { @Override public void run() { super.run(); if (get() == 2) { disposableRef.get().dispose(); } } }; Disposable disposable = worker.schedulePeriodically(counter, 1, 1, MINUTES); disposableRef.set(disposable); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); // Dispose will have happened here during the last run() execution. idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyThrowingDoesNotReschedule() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable() { @Override public void run() { super.run(); if (get() == 2) { throw new RuntimeException("Broken!"); } } }; worker.schedulePeriodically(counter, 1, 1, MINUTES); runUiThreadTasks(); assertEquals(0, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(1, counter.get()); idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); // Exception will have happened here during the last run() execution. idleMainLooper(1, MINUTES); runUiThreadTasks(); assertEquals(2, counter.get()); } @Test public void workerDisposableTracksDisposedState() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); Disposable disposable = worker.schedule(counter); assertFalse(disposable.isDisposed()); disposable.dispose(); assertTrue(disposable.isDisposed()); } @Test public void workerUnsubscriptionDuringSchedulingCancelsScheduledAction() { final AtomicReference workerRef = new AtomicReference<>(); RxJavaPlugins.setScheduleHandler(new Function() { @Override public Runnable apply(Runnable runnable) { // Purposefully unsubscribe in an asinine point after the normal unsubscribed check. workerRef.get().dispose(); return runnable; } }); Worker worker = scheduler.createWorker(); workerRef.set(worker); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test public void workerDisposeCancelsScheduled() { Worker worker = scheduler.createWorker(); CountingRunnable counter = new CountingRunnable(); worker.schedule(counter, 1, MINUTES); worker.dispose(); runUiThreadTasks(); assertEquals(0, counter.get()); } @Test public void workerUnsubscriptionDoesNotAffectOtherWorkers() { Worker workerA = scheduler.createWorker(); CountingRunnable counterA = new CountingRunnable(); workerA.schedule(counterA, 1, MINUTES); Worker workerB = scheduler.createWorker(); CountingRunnable counterB = new CountingRunnable(); workerB.schedule(counterB, 1, MINUTES); workerA.dispose(); runUiThreadTasksIncludingDelayedTasks(); assertEquals(0, counterA.get()); assertEquals(1, counterB.get()); } @Test public void workerTracksDisposedState() { Worker worker = scheduler.createWorker(); assertFalse(worker.isDisposed()); worker.dispose(); assertTrue(worker.isDisposed()); } @Test public void disposedWorkerReturnsDisposedDisposables() { Worker worker = scheduler.createWorker(); worker.dispose(); Disposable disposable = worker.schedule(new CountingRunnable()); assertTrue(disposable.isDisposed()); } @Test public void throwingActionRoutedToRxJavaPlugins() { Consumer originalErrorHandler = RxJavaPlugins.getErrorHandler(); try { final AtomicReference throwableRef = new AtomicReference<>(); RxJavaPlugins.setErrorHandler(new Consumer() { @Override public void accept(Throwable throwable) throws Exception { throwableRef.set(throwable); } }); Worker worker = scheduler.createWorker(); final NullPointerException npe = new NullPointerException(); Runnable action = new Runnable() { @Override public void run() { throw npe; } }; worker.schedule(action); runUiThreadTasks(); assertSame(npe, throwableRef.get()); } finally { RxJavaPlugins.setErrorHandler(originalErrorHandler); } } @Test public void directScheduleOnceInputValidation() { try { scheduler.scheduleDirect(null); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { scheduler.scheduleDirect(null, 1, MINUTES); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { scheduler.scheduleDirect(new CountingRunnable(), 1, null); fail(); } catch (NullPointerException e) { assertEquals("unit == null", e.getMessage()); } } @Test @Ignore("Implementation delegated to default RxJava implementation") public void directSchedulePeriodicallyInputValidation() { try { scheduler.schedulePeriodicallyDirect(null, 1, 1, MINUTES); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { scheduler.schedulePeriodicallyDirect(new CountingRunnable(), 1, -1, MINUTES); fail(); } catch (IllegalArgumentException e) { assertEquals("period < 0: -1", e.getMessage()); } try { scheduler.schedulePeriodicallyDirect(new CountingRunnable(), 1, 1, null); fail(); } catch (NullPointerException e) { assertEquals("unit == null", e.getMessage()); } } @Test public void workerScheduleOnceInputValidation() { Worker worker = scheduler.createWorker(); try { worker.schedule(null); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { worker.schedule(null, 1, MINUTES); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { worker.schedule(new CountingRunnable(), 1, null); fail(); } catch (NullPointerException e) { assertEquals("unit == null", e.getMessage()); } } @Test @Ignore("Implementation delegated to default RxJava implementation") public void workerSchedulePeriodicallyInputValidation() { Worker worker = scheduler.createWorker(); try { worker.schedulePeriodically(null, 1, 1, MINUTES); fail(); } catch (NullPointerException e) { assertEquals("run == null", e.getMessage()); } try { worker.schedulePeriodically(new CountingRunnable(), 1, -1, MINUTES); fail(); } catch (IllegalArgumentException e) { assertEquals("period < 0: -1", e.getMessage()); } try { worker.schedulePeriodically(new CountingRunnable(), 1, 1, null); fail(); } catch (NullPointerException e) { assertEquals("unit == null", e.getMessage()); } } @Test public void directScheduleSetAsync() { ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); scheduler.scheduleDirect(new Runnable() { @Override public void run() { } }); Message message = mainMessageQueue.getHead(); assertEquals(async, message.isAsynchronous()); } @Test public void workerScheduleSetAsync() { ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); Worker worker = scheduler.createWorker(); worker.schedule(new Runnable() { @Override public void run() { } }); Message message = mainMessageQueue.getHead(); assertEquals(async, message.isAsynchronous()); } @Test public void workerSchedulePeriodicallySetAsync() { ShadowMessageQueue mainMessageQueue = shadowOf(Looper.getMainLooper().getQueue()); Worker worker = scheduler.createWorker(); worker.schedulePeriodically(new Runnable() { @Override public void run() { } }, 1, 1, MINUTES); Message message = mainMessageQueue.getHead(); assertEquals(async, message.isAsynchronous()); } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/testutil/CountingRunnable.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.testutil; import java.util.concurrent.atomic.AtomicInteger; public class CountingRunnable extends AtomicInteger implements Runnable { @Override public void run() { getAndIncrement(); } } ================================================ FILE: rxandroid/src/test/java/io/reactivex/rxjava3/android/testutil/EmptyScheduler.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.testutil; import io.reactivex.rxjava3.core.Scheduler; public final class EmptyScheduler extends Scheduler { @Override public Worker createWorker() { throw new UnsupportedOperationException(); } } ================================================ FILE: sample-app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion 15 targetSdkVersion 31 versionCode 1 versionName '1.0' } lintOptions { lintConfig file('lint.xml') } compileOptions { sourceCompatibility rootProject.ext.sourceCompatibility targetCompatibility rootProject.ext.sourceCompatibility } } dependencies { implementation project(':rxandroid') } ================================================ FILE: sample-app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: sample-app/src/main/java/io/reactivex/rxjava3/android/samples/MainActivity.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.reactivex.rxjava3.android.samples; import android.app.Activity; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.View; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableSource; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.functions.Supplier; import io.reactivex.rxjava3.observers.DisposableObserver; import io.reactivex.rxjava3.schedulers.Schedulers; public class MainActivity extends Activity { private static final String TAG = "RxAndroidSamples"; private final CompositeDisposable disposables = new CompositeDisposable(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); findViewById(R.id.button_run_scheduler).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onRunSchedulerExampleButtonClicked(); } }); } @Override protected void onDestroy() { super.onDestroy(); disposables.clear(); } void onRunSchedulerExampleButtonClicked() { disposables.add(sampleObservable() // Run on a background thread .subscribeOn(Schedulers.io()) // Be notified on the main thread .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableObserver() { @Override public void onComplete() { Log.d(TAG, "onComplete()"); } @Override public void onError(Throwable e) { Log.e(TAG, "onError()", e); } @Override public void onNext(String string) { Log.d(TAG, "onNext(" + string + ")"); } })); } static Observable sampleObservable() { return Observable.defer(new Supplier>() { @Override public ObservableSource get() throws Throwable { // Do some long running operation SystemClock.sleep(5000); return Observable.just("one", "two", "three", "four", "five"); } }); } } ================================================ FILE: sample-app/src/main/res/layout/main_activity.xml ================================================