Repository: thomasnield/RxKotlinFX Branch: 2.x Commit: ad05b7abe6e6 Files: 14 Total size: 67.1 KB Directory structure: gitextract_sf6a36ys/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle/ │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src/ ├── main/ │ └── kotlin/ │ └── com/ │ └── github/ │ └── thomasnield/ │ └── rxkotlinfx/ │ ├── Nodes.kt │ ├── Observables.kt │ ├── Operators.kt │ ├── Subscribers.kt │ └── Util.kt └── test/ └── kotlin/ └── com/ └── github/ └── thomasnield/ └── rxkotlinfx/ └── OperatorsTest.kt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .gradle/ build/ *.iml *.class *.prefs *.classpath .project .idea/ gradle.properties secring.gpg ================================================ FILE: LICENSE.txt ================================================ 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. Copyright {yyyy} {name of copyright owner} 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 ================================================ ![](https://camo.githubusercontent.com/78eeb41c5378ae03cf0d23e71c3e0c9e61b0d984/687474703a2f2f692e696d6775722e636f6d2f7837726d586b652e706e67) # UNSUPPORTED, PLEASE FORK AND SUPPORT # RxKotlinFX Kotlin extensions to the [RxJavaFX](https://github.com/ReactiveX/RxJavaFX) library. This framework works especially well with [TornadoFX](https://github.com/edvin/tornadofx). See a fully functional demo [here!](https://github.com/thomasnield/rxkotlinfx-tornadofx-demo) ## Documentation [Learning RxJava with JavaFX](https://www.gitbook.com/book/thomasnield/rxjavafx-guide/details) ## Binaries Binaries and dependency information for Maven, Ivy, Gradle and others can be found at [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Cio.reactivex.rxjavafx). Example for Maven: ```xml com.github.thomasnield rxkotlinfx x.y.z ``` Gradle: ```groovy repositories { mavenCentral() } dependencies { compile 'com.github.thomasnield:rxkotlinfx:x.y.z' } ``` ## Contributing Feel free to contribute and help streamline a pragmatic UI stack with Kotlin, RxJava, and JavaFX. Speaking of stacks, this project may be used in conjunction with [TornadoFX](https://github.com/edvin/tornadofx) and [RxKotlin](https://github.com/ReactiveX/RxKotlin). Please make sure no extension naming conventions conflict with these two other libraries :) ## Features RxKotlinFX is the convergence of interoperability between [RxJava](https://github.com/ReactiveX/RxJava), [JavaFX](http://docs.oracle.com/javase/8/javase-clienttechnologies.htm), and [Kotlin](https://kotlinlang.org/). ![](http://i.imgur.com/Bhh5CX4.png) RxKotlinFX contains Kotlin extensions to [RxJavaFX](https://github.com/ReactiveX/RxJavaFX) as well as additional `Observable` operators specific to JavaFX. It also is in exporatory stages to add helpful `Node` extension functions that return Observables. This exploration is inspired by the JavaFX/Kotlin interop project [TornadoFX](https://github.com/edvin/tornadofx). Where TornadoFX handles layouts, node extensions, DI, and other JavaFX/Kotlin interoperations, this library will seek to integrate RxJava with JavaFX in the same spirit using Kotlin. The vision is to add useful extensions that put `Observable` streams as properties and functions on JavaFX components, especially where `ObservableValue` properties are not readily available. ### RxJavaFX Extensions The core API implements [RxJavaFX](https://github.com/ReactiveX/RxJavaFX) static factories as extension functions. |Target Type|Extension Function|Description| |---|---|--- |Observable<T>|toBinding()|Subscribes the `Observable` to a JavaFX `Binding` implementation. Calling `dispose()` will unsubscribe from the `Observable` |Observable<T>|toLazyBinding()|Subscribes the `Observable` to a lazy JavaFX `Binding` implementation, delaying subscription until a value is needed. Calling `dispose()` will unsubscribe from the `Observable` |Property<T>|bind(observable: Observable<T>)|Binds a `Property` to the emissions of an `Observable`, and returns the `Binding` |Binding<T>|addTo(compositeBinding: CompositeBinding)|Adds the `Binding` to a `CompositeBinding`, and returns the `Binding` |ObservableValue<T>|toObservable()|Turns a JavaFX `ObservableValue` into an RxJava `Observable` that emits the latest value |ObservableValue<T>|toObservableChanges()|Turns a JavaFX `ObservableValue` into an RxJava `Observable>` that emits the old value and new value as a pair |Dialog<T>|toObservable<T>|Returns an `Observable` that emits the given result of `Dialog`. Will be empty if no response. |Node, Window, Scene|events(eventType: EventType)| Creates an `Observable` emitting events of the given `EventType` |Node, MenuItem, ContextMenu |actionEvents()|Creates an `Observable` that emits an `ActionEvent` every time one occurs |ObservableList<T>|onChangedObservable()|Returns an `Observable>` that emits the entire `ObservableList` every time it is modified. |ObservableList<T>|additions()|Creates an `Observable` emitting `T` items that were added to the `ObservableList` |ObservableList<T>|removals()|Creates an `Observable` emitting `T` items that were removed from the `ObservableList` |ObservableList<T>|updates()|Creates an `Observable` emitting `T` items whose specified properties were updated in the `ObservableList` |ObservableList<T>|changes()|Creates an `Observable>` emitting `ListChange` items, which pairs each item with an `ADDED`, `REMOVED`, or `UPDATED` flag |ObservableList<T>|distinctChanges()|Creates an `Observable>` emitting *distinct* `ListChange` items. It will only emit the first `ADDED` item `T` and not emit dupes, and will only emit the `REMOVED` item `T` when no more dupes exist |ObservableList<T>|distinctChanges(mapper: (T) -> R)|Creates an `Observable>` emitting *distinct* `ListChange` items based off the `mapper`'s definition of a distinct value `R`. It will only emit the first `ADDED` item `T` and not emit dupes, and will only emit the `REMOVED` item `T` when no more dupes exist |ObservableList<T>|distinctMappingChanges(mapper: (T) -> R)|Creates an `Observable>` emitting *distinct* `ListChange` mappings based off the `mapper`'s definition of a distinct value `R`. It will only emit the first `ADDED` item `R` and not emit dupes, and will only emit the `REMOVED` item `R` when no more dupes exist ##### Observable of Button ActionEvents ```kotlin val myButton = Button("Press Me") val subscription = myButton.actionEvents().subscribe { println("Pressed!") } ``` ##### Creating a Reactive Binding ```kotlin val myButton = Button("Press Me") val countBinding = myButton.actionEvents().map { 1 } .scan(0, { x,y -> x + y }) .map { it.toString() } .toBinding() val myLabel = Label() myLabel.textProperty().bind(countBinding) ``` ##### Observable of ObservableList Events ```kotlin val items = FXCollections.observableArrayList("Alpha", "Beta", "Gamma") val changes = items.changes() changes.filter { it.flag == Flag.ADDED } .map { it.value } .subscribe { println("ADDED $it") } items.add("Delta") items.add("Epsilon") ``` ###### OUTPUT ``` ADDED Delta ADDED Epsilon ``` ##### Turning an ObservableList into a Hot Concatenation ```kotlin val observableList = FXCollections.observableArrayList() observableList.onChangedObservable() .flatMap { it.toObservable().map { it.length } .map { it.toString() } .reduce { s1,s2 -> s1 + "|" + s2 } } .subscribe { println(it) } observableList.setAll("Alpha", "Beta", "Gamma") observableList.add("Delta") observableList.add("Epsilon") observableList.remove("Alpha") ``` ###### OUTPUT ``` 5|4|5 5|4|5|5 5|4|5|5|7 4|5|5|7 ``` ##### Using a Dialog or Alert ```kotlin val dialog = Alert(AlertType.CONFIRMATION, "Are you sure you want to continue?") dialog.toObservable().filter { it == ButtonType.YES } .subscribe { println("You pressed YES") } ``` ##### Using and Disposing CompositeBinding ```kotlin val binding1: Binding = ... val binding2: Binding = ... //adding one at a time val bindings = CompositeBinding() val bindings += binding1 val bindings += binding2 //or all at once val bindings = CompositeBinding(binding1,binding2) //do stuff, then dispose Bindings bindings.dispose() ``` ### Operators RxKotlinFX has a growing list of operators placed as extension functions onto `Observable` that aid interoperability with JavaFX. |Operator|Description| |----|-----| |observeOnFx()|Schedules the emissions to be observed on the JavaFX thread |subscribeOnFx()|Schedules the source `Observable` to emit items on the JavaFX thread |doOnNextFx()|Executes the specified action on the FX thread for each emission |doOnErrorFx()|Executes the specified action on the FX thread when an error is emitted |doOnCompleteFx()|Executes the specified action on the FX thread when the `Observable` calls `onComplete()` |doOnSubscribeFx()|Executes the specified action on the FX thread when the `Observable` is first subscribed |doOnTerminateFx()|Executes the specified action on the FX thread when the `Observable` calls `onComplete()` or `onError()` |doOnDisposeFx()|Executes the specified action on the FX thread when the `Observable` is unsubscribed |doOnNextCount()|Executes the specified action with the cumulative count of emissions for that emission |doOnErrorCount()|Executes the specified action with the cumulative count of emissions when an error is emitted |doOnCompleteCount()|Executes the specified action with the total emission count when `onComplete()` is called |doOnNextCountFx()|Same as `doOnNextCount()` except action is executed on FX thread |doOnErrorCountFx()|Same as `doOnErrorCount()` except action is executed on FX thread |doOnCompleteCountFx()|Same as `doOnCompleteCount()` except action is executed on FX thread The `doOnXXXCount()` operators are especially helpful for providing a status update of how many items have been "processed" by an `Observable`. ```kotlin val source = Observable.range(1,1000) val processedCountLabel = Label() source.map { it * 10 } .doOnNextFx { processedCountLabel.text = "Processed $it items" } .subsribe { doSomethingWith(it) } ``` ### Control Extensions The rest of the project will likely add convenient extension functions to emit events as `Observable` values, [much like the TornadoFX project has done](https://github.com/edvin/tornadofx/blob/master/src/main/java/tornadofx/Nodes.kt). For example, helpful `Observable` extension functions and properties can be added to `TableView` and `ListView`, such as selection events. ```kotlin val tableView: TableView = ... val selections: Observable = tableView.itemSelections val rowIndexSelections: Observable = tableView.rowIndexSelections ``` Check releases as well the [Nodes code file](https://github.com/thomasnield/RxKotlinFX/blob/master/src/main/kotlin/rx/javafx/kt/Nodes.kt) to see a list of available extensions. Feel free to contribute if you see any missing. ## Bugs and Feedback For bugs, questions and discussions please use the [Github Issues](https://github.com/thomasnield/RxKotlinFx/issues). ## LICENSE 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 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: build.gradle ================================================ buildscript { ext.kotlin_version = '1.1.60' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: "kotlin" apply plugin: 'maven' apply plugin: 'signing' sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" compile 'io.reactivex.rxjava2:rxjavafx:2.2.2' testCompile 'junit:junit:4.12' } task javadocJar(type: Jar) { classifier = 'javadoc' from javadoc } task sourcesJar(type: Jar) { classifier = 'sources' from sourceSets.main.allSource } artifacts { archives javadocJar, sourcesJar } signing { sign configurations.archives } group = "com.github.thomasnield" archivesBaseName = "rxkotlinfx" version = "2.2.2" uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { authentication(userName: ossrhUsername, password: ossrhPassword) } snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { authentication(userName: ossrhUsername, password: ossrhPassword) } pom.project { name 'RxKotlinFX' packaging 'jar' // optionally artifactId can be defined here description 'Interoperability library for RxJava, JavaFX, and Kotlin' url 'https://github.com/thomasnield/RxKotlinFX' scm { connection 'scm:git:git://github.com/thomasnield/RxKotlinFX.git' developerConnection 'scm:git:git@github.com:thomasnield/RxKotlinFX.git' url 'https://github.com/thomasnield/RxKotlinFX.git' } licenses { license { name 'The Apache License, Version 2.0' url 'http://www.apache.org/licenses/LICENSE-2.0.txt' } } developers { developer { id 'thomasnield' name 'Thomas Nield' email 'thomasnield@live.com' } } } } } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Sat Feb 25 20:14:08 CST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip ================================================ FILE: gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # 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 case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # 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 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" ] ; 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, switch paths to Windows format before running java if $cygwin ; 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=$((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 # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: gradlew.bat ================================================ @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 @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= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @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 init 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 init 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 :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :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 %CMD_LINE_ARGS% :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: src/main/kotlin/com/github/thomasnield/rxkotlinfx/Nodes.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.Observable import javafx.scene.control.* /** * Returns an [Observable] emitting integer values for selected row indexes. */ val TableView.rowIndexSelections: Observable get() = itemSelections.map { selectionModel.selectedIndex } /** * Returns an [Observable] emitting integer values for selected column indexes. */ val TableView.columnIndexSelections: Observable get() = selectionModel.selectedCells .additions().map { it.column } /** * Returns an [Observable] emitting selected items for the given TableView */ val TableView.itemSelections: Observable get() = selectionModel.selectedItemProperty().toObservable() /** * Returns an [Observable] emitting single selected items for the given [ListView] */ val ListView.itemSelections: Observable get() = selectionModel.selectedItems.additions() /** * Returns an [Observable] emitting single selected items for the given [ComboBox] */ val ComboBox.valueSelections: Observable get() = valueProperty().toObservable() /** * Returns an [Observable] emitting text value inputs for the given [TextField] */ val TextField.textValues: Observable get() = textProperty().toObservable() /** * Returns an [Observable] emitting [Tab] selections for the given [TabPane] */ val TabPane.tabSelections: Observable get() = selectionModel.selectedItemProperty().toObservable() ================================================ FILE: src/main/kotlin/com/github/thomasnield/rxkotlinfx/Observables.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import io.reactivex.rxjavafx.observables.JavaFxObservable import io.reactivex.rxjavafx.observers.JavaFxObserver import io.reactivex.rxjavafx.observers.JavaFxSubscriber import io.reactivex.rxjavafx.sources.SetChange import javafx.beans.binding.Binding import javafx.beans.value.ObservableValue import javafx.collections.ObservableList import javafx.collections.ObservableMap import javafx.collections.ObservableSet import javafx.event.Event import javafx.event.EventType import javafx.scene.Node import javafx.scene.Scene import javafx.scene.control.ContextMenu import javafx.scene.control.Dialog import javafx.scene.control.MenuItem import javafx.stage.Window import javafx.stage.WindowEvent import java.util.* /** * Turns an Observable into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal. */ fun Observable.toBinding(actionOp: (ObservableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxObserver.toBinding((transformer?.let { this.compose(it) }?:this)) } /** * Turns an Flowable into a JavaFX Binding. Calling the Binding's dispose() method will handle the unsubscription. */ fun Flowable.toBinding(actionOp: (FlowableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = FlowableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxSubscriber.toBinding((transformer?.let { this.compose(it) }?:this)) } /** * Turns an Observable into a JavaFX Binding with a nullSentinel `T` acting as a placeholder for null values. Calling the Binding's dispose() method will handle the disposal. */ fun Observable.toNullBinding(nullSentinel: T, actionOp: (ObservableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxObserver.toNullBinding((transformer?.let { this.compose(it) }?:this), nullSentinel) } /** * Turns an Flowable into a JavaFX Binding with a nullSentinel `T` acting as a placeholder for null values. Calling the Binding's dispose() method will handle the disposal. */ fun Flowable.toNullBinding(nullSentinel: T, actionOp: (FlowableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = FlowableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxSubscriber.toNullBinding((transformer?.let { this.compose(it) }?:this), nullSentinel) } /** * Turns an Observable into a JavaFX Binding that automatically unwraps the Optional to a nullable value. Calling the Binding's dispose() method will handle the disposal. */ fun Observable>.toNullableBinding(actionOp: (ObservableBindingSideEffects>.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects>() it.invoke(sideEffects) sideEffects.transformer } return JavaFxObserver.toNullableBinding((transformer?.let { this.compose(it) }?:this)) } /** * Turns an `Flowable>` into a JavaFX Binding that automatically unwraps the Optional to a nullable value. Calling the Binding's dispose() method will handle the unsubscription. */ fun Flowable>.toNullableBinding(actionOp: (FlowableBindingSideEffects>.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = FlowableBindingSideEffects>() it.invoke(sideEffects) sideEffects.transformer } return JavaFxSubscriber.toNullableBinding((transformer?.let { this.compose(it) }?:this)) } /** * Turns an Observable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Observable.toLazyBinding() = JavaFxObserver.toLazyBinding(this) /** * Turns a Flowable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Flowable.toLazyBinding() = JavaFxSubscriber.toLazyBinding(this) /** * Turns an `Observable>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Observable>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this) /** * Turns a `Flowable>` into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Flowable>.toLazyNullableBinding() = JavaFxSubscriber.toLazyNullableBinding(this) /** * Turns a Single into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal. */ fun Single.toBinding(actionOp: (ObservableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxObserver.toBinding((transformer?.let { this.toObservable().compose(it) }?:this.toObservable())) } /** * Turns a Single into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Single.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable()) /** * Turns a `Single>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Single>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this.toObservable()) /** * Turns a Maybe into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal. */ fun Maybe.toBinding(actionOp: (ObservableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } return JavaFxObserver.toBinding((transformer?.let { this.toObservable().compose(it) }?:this.toObservable())) } /** * Turns a Maybe into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Maybe.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable()) /** * Turns a `Maybe>` into a lazy JavaFX Binding that automatically unwraps the Optional to a nullable value, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Maybe>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this.toObservable()) /** * Turns an Observable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Observable.toLazyBinding(errorHandler: (Throwable) -> Unit) = JavaFxObserver.toLazyBinding(this,errorHandler) /** * Turns a Flowable into a lazy JavaFX Binding, by lazy meaning it will delay subscription until `getValue()` is requested. Calling the Binding's dispose() method will handle the unsubscription. */ fun Flowable.toLazyBinding(errorHandler: (Throwable) -> Unit) = JavaFxSubscriber.toLazyBinding(this,errorHandler) /** * Create an rx Observable from a javafx ObservableValue * @param the type of the observed value * @return an Observable emitting values as the wrapped ObservableValue changes */ fun ObservableValue.toObservable() = JavaFxObservable.valuesOf(this) /** * Create an rx Observable from a javafx ObservableValue * @param the type of the observed value * @param nullSentinel the default sentinel value emitted when the observable is null * @return an Observable emitting values as the wrapped ObservableValue changes */ fun ObservableValue.toObservable(nullSentinel: T) = JavaFxObservable.valuesOf(this, nullSentinel) /** * Create an rx Observable from a javafx ObservableValue, emitting nullable values as Java 8 `Optional` types * @param the type of the observed value * @return an Observable emitting `Optional` values as the wrapped ObservableValue changes */ fun ObservableValue.toNullableObservable() = JavaFxObservable.nullableValuesOf(this) /** * Create an rx Observable from a javafx Observable, emitting it when an invalidation occursk * @return an rx Observable emitting the JavaFX Observable every time it is invalidated */ fun javafx.beans.Observable.invalidations() = JavaFxObservable.invalidationsOf(this) /** * Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs * @param the type of the observed value * @return an Observable emitting values as the wrapped ObservableValue changes */ fun ObservableValue.toObservableChanges() = JavaFxObservable.changesOf(this) /** * Create an rx Observable from a javafx ObservableValue, and emits changes with old and new non-null value pairs * @param the type of the observed value * @return an Observable emitting non-null values as the wrapped ObservableValue changes */ fun ObservableValue.toObservableChangesNonNull() = JavaFxObservable.nonNullChangesOf(this) /** * Creates an observable corresponding to javafx ContextMenu action events. * @return An Observable of UI ActionEvents */ fun ContextMenu.actionEvents() = JavaFxObservable.actionEventsOf(this) /** * Creates an observable corresponding to javafx MenuItem action events. * * @param menuItem The target of the ActionEvents * @return An Observable of UI ActionEvents */ fun MenuItem.actionEvents() = JavaFxObservable.actionEventsOf(this) /** * Creates an observable corresponding to javafx Node action events. * @return An Observable of UI ActionEvents */ fun Node.actionEvents() = JavaFxObservable.actionEventsOf(this) /** * Creates an observable corresponding to javafx Node events. * @param eventType The type of the observed UI events * @return An Observable of UI events, appropriately typed */ fun Node.events(eventType: EventType) = JavaFxObservable.eventsOf(this, eventType) /** * Create an rx Observable from a javafx ObservableValue * @param the type of the observed value * @return an Observable emitting values as the wrapped ObservableValue changes */ fun Scene.events(eventType: EventType) = JavaFxObservable.eventsOf(this,eventType) /** * Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs * @param the type of the observed value * @return an Observable emitting values as the wrapped ObservableValue changes */ fun Window.events(eventType: EventType) = JavaFxObservable.eventsOf(this,eventType) /** * Creates an observable that emits an ObservableList every time it is modified * @return An Observable emitting the ObservableList each time it changes */ fun ObservableList.onChangedObservable() = JavaFxObservable.emitOnChanged(this) /** * Creates an observable that emits all removal items from an ObservableList * @return An Observable emitting items removed from the ObservableList */ fun ObservableList.removals() = JavaFxObservable.removalsOf(this) /** * Creates an observable that emits all additions to an ObservableList * @return An Observable emitting items added to the ObservableList */ fun ObservableList.additions() = JavaFxObservable.additionsOf(this) /** * Creates an observable that emits all updated items from an ObservableList. * If you declare an ObservableList that listens to one or more properties of each element, * you can emit the changed items every time these properties are modified *
ObservableList sourceList = FXCollections.observableArrayList(user -> new javafx.beans.Observable[]{user.age} );
* @return An Observable emitting items updated in the ObservableList */ fun ObservableList.updates() = JavaFxObservable.updatesOf(this) /** * Emits all added, removed, and updated items from an ObservableList * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableList.changes() = JavaFxObservable.changesOf(this) /** * Emits distinctly added and removed items from an ObservableList. * If dupe items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED item. * When the last dupe is removed, only then will it fire a REMOVED item. * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableList.distinctChanges() = JavaFxObservable.distinctChangesOf(this) /** * Emits distinctly added and removed items item from an ObservableList. * If dupe mapped R items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED T item. * When the last dupe is removed, only then will it fire a REMOVED T item. * @return An Observable emitting changed mapped items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableList.distinctChanges(mapper: ((T) -> R)) = JavaFxObservable.distinctChangesOf(this,mapper) /** * Emits distinctly added and removed mappings to each R item from an ObservableList. * If dupe mapped R items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED R item. * When the last dupe is removed, only then will it fire a REMOVED R item. * @return An Observable emitting changed mapped items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableList.distinctMappingChanges(mapper: ((T) -> R)) = JavaFxObservable.distinctMappingsOf(this,mapper) /** * Creates an observable that emits an ObservableMap every time it is modified * @return An Observable emitting the ObservableMap each time it changes */ fun ObservableMap.onChangedObservable() = JavaFxObservable.emitOnChanged(this) /** * Creates an observable that emits all removal items from an ObservableMap * @return An Observable emitting items removed from the ObservableMap */ fun ObservableMap.removals() = JavaFxObservable.removalsOf(this) /** * Creates an observable that emits all additions to an ObservableMap * @return An Observable emitting items added to the ObservableMap */ fun ObservableMap.additions() = JavaFxObservable.additionsOf(this) /** * Emits all added, removed, and updated items from an ObservableMap * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableMap.changes() = JavaFxObservable.changesOf(this) /** * Creates an observable that emits an ObservableSet every time it is modified * @return An Observable emitting the ObservableSet each time it changes */ fun ObservableSet.onChangedObservable() = JavaFxObservable.emitOnChanged(this) /** * Creates an observable that emits all removal items from an ObservableSet * @return An Observable emitting items removed from the ObservableSet */ fun ObservableSet.removals() = JavaFxObservable.removalsOf(this) /** * Creates an observable that emits all additions to an ObservableSet * @return An Observable emitting items added to the ObservableSet */ fun ObservableSet.additions() = JavaFxObservable.additionsOf(this) /** * Emits all added, removed, and updated items from an ObservableSet * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flags */ fun ObservableSet>.changes() = JavaFxObservable.changesOf(this) /** * Emits the response `T` for a given `Dialog`. If no response is provided the Maybe will be empty. */ fun Dialog.toMaybe() = JavaFxObservable.fromDialog(this)!! ================================================ FILE: src/main/kotlin/com/github/thomasnield/rxkotlinfx/Operators.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.* import io.reactivex.rxjavafx.schedulers.JavaFxScheduler import io.reactivex.rxjavafx.transformers.FxFlowableTransformers import io.reactivex.rxjavafx.transformers.FxObservableTransformers import javafx.application.Platform /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Observable#observeOn(JavaFxScheduler.platform()) */ fun Observable.observeOnFx() = observeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Flowable#observeOn(JavaFxScheduler.platform()) */ fun Flowable.observeOnFx() = observeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Single#observeOn(JavaFxScheduler.platform()) */ fun Single.observeOnFx() = observeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Maybe#observeOn(JavaFxScheduler.platform()) */ fun Maybe.observeOnFx() = observeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Completable#observeOn(JavaFxScheduler.platform()) */ fun Completable.observeOnFx() = observeOn(JavaFxScheduler.platform()) /** * Instructs the source Observable to emit items on the JavaFX Thread. * This is the same as calling Observable#subscribeOn(JavaFxScheduler.platform()) */ fun Observable.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform()) /** * Instructs the source Flowable to emit items on the JavaFX Thread. * This is the same as calling Flowable#subscribeOn(JavaFxScheduler.platform()) */ fun Flowable.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Single#subscribeOnFx(JavaFxScheduler.platform()) */ fun Single.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Maybe#subscribeOnFx(JavaFxScheduler.platform()) */ fun Maybe.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform()) /** * Observes the emissions on the JavaFX Thread. * This is the same as calling Completable#subscribeOnFx(JavaFxScheduler.platform()) */ fun Completable.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform()) /** * Performs the provided onNext action on the FX thread */ inline fun Observable.doOnNextFx(crossinline onNext: (T) -> Unit): Observable = doOnNext { Platform.runLater { onNext.invoke(it) } } /** * Performs the provided onNext action on the FX thread */ inline fun Flowable.doOnNextFx(crossinline onNext: (T) -> Unit): Flowable = doOnNext { Platform.runLater { onNext.invoke(it) } } /** * Performs the provided onError action on the FX thread */ inline fun Observable.doOnErrorFx(crossinline onError: (Throwable) -> Unit): Observable = doOnError { Platform.runLater { onError.invoke(it) } } /** * Performs the provided onError action on the FX thread */ inline fun Flowable.doOnErrorFx(crossinline onError: (Throwable) -> Unit): Flowable = doOnError { Platform.runLater { onError.invoke(it) } } /** * Performs the provided onComplete action on the FX thread */ inline fun Observable.doOnCompleteFx(crossinline onComplete: () -> Unit): Observable = doOnComplete { Platform.runLater { onComplete.invoke() } } /** * Performs the provided onComplete action on the FX thread */ inline fun Flowable.doOnCompleteFx(crossinline onComplete: () -> Unit): Flowable = doOnComplete { Platform.runLater { onComplete.invoke() } } /** * Performs the provided onSubscribe action on the FX thread */ inline fun Observable.doOnSubscribeFx(crossinline onSubscribe: () -> Unit): Observable = doOnSubscribe { Platform.runLater { onSubscribe.invoke() } } /** * Performs the provided onSubscribe action on the FX thread */ inline fun Flowable.doOnSubscribeFx(crossinline onSubscribe: () -> Unit): Flowable = doOnSubscribe { Platform.runLater { onSubscribe.invoke() } } /** * Performs the provided onTerminate action on the FX thread */ inline fun Observable.doOnTerminateFx(crossinline onTerminate: () -> Unit): Observable = doOnTerminate { Platform.runLater { onTerminate.invoke() } } /** * Performs the provided onTerminate action on the FX thread */ inline fun Flowable.doOnTerminateFx(crossinline onTerminate: () -> Unit): Flowable = doOnTerminate { Platform.runLater { onTerminate.invoke() } } /** * Performs the provided onDispose action on the FX thread */ inline fun Observable.doOnDisposeFx(crossinline onDispose: () -> Unit): Observable = this.doOnDispose { Platform.runLater { onDispose.invoke() } } /** * Performs the provided onDispose action on the FX thread */ inline fun Flowable.doOnCancelFx(crossinline onDispose: () -> Unit): Flowable = this.doOnCancel { Platform.runLater { onDispose.invoke() } } /** * Executes side effect with the accumulating count of emissions for each onNext() call */ fun Observable.doOnNextCount(onNext: (Int) -> Unit): Observable = compose(FxObservableTransformers.doOnNextCount(onNext)) /** * Executes side effect with the accumulating count of emissions for each onNext() call */ fun Flowable.doOnNextCount(onNext: (Int) -> Unit): Flowable = compose(FxFlowableTransformers.doOnNextCount(onNext)) /** * Executes side effect with the total count of emissions for the onComplete() call */ fun Observable.doOnCompleteCount(onComplete: (Int) -> Unit): Observable = compose(FxObservableTransformers.doOnCompleteCount(onComplete)) /** * Executes side effect with the total count of emissions for the onComplete() call */ fun Flowable.doOnCompleteCount(onComplete: (Int) -> Unit): Flowable = compose(FxFlowableTransformers.doOnCompleteCount(onComplete)) /** * Executes side effect with the total count of emissions for an onError() call */ fun Observable.doOnErrorCount(onError: (Int) -> Unit): Observable = compose(FxObservableTransformers.doOnErrorCount(onError)) /** * Executes side effect with the total count of emissions for an onError() call */ fun Flowable.doOnErrorCount(onError: (Int) -> Unit): Flowable = compose(FxFlowableTransformers.doOnErrorCount(onError)) /** * Executes side effect on FX thread with the accumulating count of emissions for each onNext() call */ fun Observable.doOnNextCountFx(onNext: (Int) -> Unit) = doOnNextCount { Platform.runLater { onNext.invoke(it) } } /** * Executes side effect on FX thread with the accumulating count of emissions for each onNext() call */ fun Flowable.doOnNextCountFx(onNext: (Int) -> Unit) = doOnNextCount { Platform.runLater { onNext.invoke(it) } } /** * Executes side effect on FX thread with the total count of emissions for the onComplete() call */ fun Observable.doOnCompleteCountFx(onComplete: (Int) -> Unit) = doOnCompleteCount { Platform.runLater { onComplete.invoke(it) } } /** * Executes side effect on FX thread with the total count of emissions for the onComplete() call */ fun Flowable.doOnCompleteCountFx(onComplete: (Int) -> Unit) = doOnCompleteCount { Platform.runLater { onComplete.invoke(it) } } /** * Executes side effect on FX thread with the total count of emissions for the onError() call */ fun Observable.doOnErrorCountFx(onError: (Int) -> Unit) = doOnErrorCount { Platform.runLater { onError.invoke(it) } } /** * Executes side effect on FX thread with the total count of emissions for the onError() call */ fun Flowable.doOnErrorCountFx(onError: (Int) -> Unit) = doOnErrorCount { Platform.runLater { onError.invoke(it) } } ================================================ FILE: src/main/kotlin/com/github/thomasnield/rxkotlinfx/Subscribers.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.Flowable import io.reactivex.FlowableTransformer import io.reactivex.Observable import io.reactivex.ObservableTransformer import io.reactivex.rxjavafx.subscriptions.CompositeBinding import javafx.beans.binding.Binding import javafx.beans.property.Property /** * Binds the `Property` to an RxJava `Observable`, * meaning it will be bounded to show the latest emissions of that `Observable`. * The `Binding` is also returned so caller can be dispose it later if needed * @return `Binding` */ fun Property.bind(observable: Observable, actionOp: (ObservableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = ObservableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } val binding = (transformer?.let { observable.compose(it) }?:observable).toBinding() bind(binding) return binding } /** * Binds the `Property` to an RxJava `Flowable`, * meaning it will be bounded to show the latest emissions of that `Flowable`. * The `Binding` is also returned so caller can be dispose it later if needed * @return `Binding` */ fun Property.bind(flowable: Flowable, actionOp: (FlowableBindingSideEffects.() -> Unit)? = null): Binding { val transformer = actionOp?.let { val sideEffects = FlowableBindingSideEffects() it.invoke(sideEffects) sideEffects.transformer } val binding = (transformer?.let { flowable.compose(it) }?:flowable).toBinding() bind(binding) return binding } fun Binding.addTo(compositeBinding: CompositeBinding): Binding { compositeBinding.add(this) return this } operator fun CompositeBinding.plusAssign(binding: Binding) = add(binding) operator fun CompositeBinding.plusAssign(compositeBinding: CompositeBinding) = add(compositeBinding) operator fun CompositeBinding.minusAssign(binding: Binding) = remove(binding) operator fun CompositeBinding.minusAssign(compositeBinding: CompositeBinding) = remove(compositeBinding) class ObservableBindingSideEffects { private var onNextAction: ((T) -> Unit)? = null private var onCompleteAction: (() -> Unit)? = null private var onErrorAction: ((ex: Throwable) -> Unit)? = null fun onNext(onNext: (T) -> Unit): Unit { onNextAction = onNext } fun onComplete(onComplete: () -> Unit): Unit { onCompleteAction = onComplete } fun onError(onError: (ex: Throwable) -> Unit): Unit { onErrorAction = onError } internal val transformer: ObservableTransformer get() = ObservableTransformer { obs -> var withActions: Observable = obs withActions = onNextAction?.let { withActions.doOnNext(onNextAction) } ?: withActions withActions = onCompleteAction?.let { withActions.doOnComplete(onCompleteAction) } ?: withActions withActions = onErrorAction?.let { withActions.doOnError(onErrorAction) } ?: withActions withActions } } class FlowableBindingSideEffects { private var onNextAction: ((T) -> Unit)? = null private var onCompleteAction: (() -> Unit)? = null private var onErrorAction: ((ex: Throwable) -> Unit)? = null fun onNext(onNext: (T) -> Unit): Unit { onNextAction = onNext } fun onComplete(onComplete: () -> Unit): Unit { onCompleteAction = onComplete } fun onError(onError: (ex: Throwable) -> Unit): Unit { onErrorAction = onError } internal val transformer: FlowableTransformer get() = FlowableTransformer { obs -> var withActions: Flowable = obs withActions = onNextAction?.let { withActions.doOnNext(onNextAction) } ?: withActions withActions = onCompleteAction?.let { withActions.doOnComplete(onCompleteAction) } ?: withActions withActions = onErrorAction?.let { withActions.doOnError(onErrorAction) } ?: withActions withActions } } ================================================ FILE: src/main/kotlin/com/github/thomasnield/rxkotlinfx/Util.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.Observable import java.util.* @Deprecated("Don't use this anymore. Implement yourself.", ReplaceWith("Single.just(this).filter { it.isPresent }.map { it.get() }", "io.reactivex.Observable")) fun Optional.toObservable() = Observable.just(this) .filter { it.isPresent } .map { it.get() } ================================================ FILE: src/test/kotlin/com/github/thomasnield/rxkotlinfx/OperatorsTest.kt ================================================ package com.github.thomasnield.rxkotlinfx import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import javafx.application.Platform import javafx.embed.swing.JFXPanel import org.junit.Assert.assertTrue import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger class OperatorsTest { init { JFXPanel() } @org.junit.Test fun doOnNextFxTest() { val latch = CountDownLatch(1) Observable.just("Alpha").observeOn(Schedulers.io()).doOnNextFx { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) } @org.junit.Test fun doOnCompletedFxTest() { val latch = CountDownLatch(1) Observable.just("Alpha").observeOn(Schedulers.io()).doOnCompleteFx() { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) } @org.junit.Test fun doOnSubscribeFx() { val latch = CountDownLatch(1) Observable.just("Alpha").observeOn(Schedulers.io()).doOnSubscribeFx { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) } @org.junit.Test fun doOnTerminateFx() { val latch = CountDownLatch(1) Observable.just("Alpha").observeOn(Schedulers.io()).doOnTerminateFx { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) } @org.junit.Test fun doOnUnsubscribeFxTest() { val latch = CountDownLatch(1) val subscription = Observable.interval(1, TimeUnit.SECONDS).doOnDisposeFx { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.subscribe() Thread.sleep(3000) subscription.dispose() latch.await(10, TimeUnit.SECONDS) } @org.junit.Test fun doOnErrorFxTest() { val latch = CountDownLatch(1) Observable.just(5).map { it / 0 }.observeOn(Schedulers.io()).doOnErrorFx { assertTrue(Platform.isFxApplicationThread()) latch.countDown() }.onErrorResumeNext(Observable.empty()).subscribe() latch.await() } @org.junit.Test fun doOnNextCountTest() { val items: MutableList = ArrayList() Observable.just("Alpha","Beta","Gamma") .doOnNextCount { items.add(it) } .subscribe() assertTrue(items.containsAll(listOf(1,2,3))) } @org.junit.Test fun doOnCompletedCountTest() { var value: Int? = null Observable.just("Alpha","Beta","Gamma") .doOnCompleteCount { value = it } .subscribe() assertTrue(value != null && value == 3) } @org.junit.Test fun doOnErrorCountTest() { var value: Int? = null Observable.just(1,2,0,3) .map { 10 / it } .doOnErrorCount { value = it } .subscribe() assertTrue(value != null && value == 2) } @org.junit.Test fun doOnNextCountFxTest() { val latch = CountDownLatch(3) var sum: Int = 0 Observable.just(1,2,3) .doOnNextCountFx { assertTrue(Platform.isFxApplicationThread()) sum += it latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) assert(sum == 6) } @org.junit.Test fun doOnCompletedCountFxTest() { val latch = CountDownLatch(1) var value: Int? = null Observable.just("Alpha","Beta","Gamma") .doOnCompleteCountFx { assertTrue(Platform.isFxApplicationThread()) value = it latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) assertTrue(value == 3) } @org.junit.Test fun doOnErrorCountFxTest() { val latch = CountDownLatch(1) var value: Int? = null Observable.just(1,3,0,5) .map { 10 / it } .doOnErrorCountFx { assertTrue(Platform.isFxApplicationThread()) value = it latch.countDown() }.subscribe() latch.await(10, TimeUnit.SECONDS) assertTrue(value == 2) } @org.junit.Test fun bindingSideEffectsTest() { val counter = AtomicInteger(0) Observable.just(1,2,3) .toBinding { onNext { counter.incrementAndGet() } onComplete { counter.incrementAndGet() } } assertTrue(counter.get() == 4) } @org.junit.Test fun bindingSideEffectsErrorTest() { val counter = AtomicInteger(0) Observable.error(Exception("Test")) .toBinding { onError { counter.incrementAndGet() } } assertTrue(counter.get() == 1) } }