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
================================================

# 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
<dependency>
<groupId>com.github.thomasnield</groupId>
<artifactId>rxkotlinfx</artifactId>
<version>x.y.z</version>
</dependency>
```
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/).

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<T>` to a JavaFX `Binding` implementation. Calling `dispose()` will unsubscribe from the `Observable<T>`
|Observable<T>|toLazyBinding()|Subscribes the `Observable<T>` to a lazy JavaFX `Binding` implementation, delaying subscription until a value is needed. Calling `dispose()` will unsubscribe from the `Observable<T>`
|Property<T>|bind(observable: Observable<T>)|Binds a `Property<T>` to the emissions of an `Observable<T>`, 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<T>` into an RxJava `Observable<T>` that emits the latest value
|ObservableValue<T>|toObservableChanges()|Turns a JavaFX `ObservableValue<T>` into an RxJava `Observable<Change<T>>` that emits the old value and new value as a pair
|Dialog<T>|toObservable<T>|Returns an `Observable<T>` that emits the given result of `Dialog<T>`. Will be empty if no response.
|Node, Window, Scene|events(eventType: EventType<T>)| 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<ObservableList<T>>` that emits the entire `ObservableList<T>` every time it is modified.
|ObservableList<T>|additions()|Creates an `Observable<T>` emitting `T` items that were added to the `ObservableList<T>`
|ObservableList<T>|removals()|Creates an `Observable<T>` emitting `T` items that were removed from the `ObservableList<T>`
|ObservableList<T>|updates()|Creates an `Observable<T>` emitting `T` items whose specified properties were updated in the `ObservableList<T>`
|ObservableList<T>|changes()|Creates an `Observable<ListChange<T>>` emitting `ListChange<T>` items, which pairs each item with an `ADDED`, `REMOVED`, or `UPDATED` flag
|ObservableList<T>|distinctChanges()|Creates an `Observable<ListChange<T>>` emitting *distinct* `ListChange<T>` 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<ListChange<T>>` emitting *distinct* `ListChange<T>` 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<ListChange<R>>` emitting *distinct* `ListChange<R>` 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<String>()
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<MyItem> = ...
val selections: Observable<MyItem> = tableView.itemSelections
val rowIndexSelections: Observable<Int> = 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
<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: 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 <T> TableView<T>.rowIndexSelections: Observable<Int>
get() = itemSelections.map { selectionModel.selectedIndex }
/**
* Returns an [Observable] emitting integer values for selected column indexes.
*/
val <T> TableView<T>.columnIndexSelections: Observable<Int>
get() = selectionModel.selectedCells
.additions().map { it.column }
/**
* Returns an [Observable] emitting selected items for the given TableView
*/
val <T> TableView<T>.itemSelections: Observable<T>
get() = selectionModel.selectedItemProperty().toObservable()
/**
* Returns an [Observable] emitting single selected items for the given [ListView]
*/
val <T> ListView<T>.itemSelections: Observable<T>
get() = selectionModel.selectedItems.additions()
/**
* Returns an [Observable] emitting single selected items for the given [ComboBox]
*/
val <T> ComboBox<T>.valueSelections: Observable<T>
get() = valueProperty().toObservable()
/**
* Returns an [Observable] emitting text value inputs for the given [TextField]
*/
val TextField.textValues: Observable<String>
get() = textProperty().toObservable()
/**
* Returns an [Observable] emitting [Tab] selections for the given [TabPane]
*/
val TabPane.tabSelections: Observable<Tab>
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 <T> Observable<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
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 <T> Flowable<T>.toBinding(actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<T>()
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 <T> Observable<T>.toNullBinding(nullSentinel: T, actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
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 <T> Flowable<T>.toNullBinding(nullSentinel: T, actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<T>()
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 <T> Observable<Optional<T>>.toNullableBinding(actionOp: (ObservableBindingSideEffects<Optional<T>>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<Optional<T>>()
it.invoke(sideEffects)
sideEffects.transformer
}
return JavaFxObserver.toNullableBinding((transformer?.let { this.compose(it) }?:this))
}
/**
* Turns an `Flowable<Optional<T>>` into a JavaFX Binding that automatically unwraps the Optional to a nullable value. Calling the Binding's dispose() method will handle the unsubscription.
*/
fun <T> Flowable<Optional<T>>.toNullableBinding(actionOp: (FlowableBindingSideEffects<Optional<T>>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<Optional<T>>()
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 <T> Observable<T>.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 <T> Flowable<T>.toLazyBinding() = JavaFxSubscriber.toLazyBinding(this)
/**
* Turns an `Observable<Optional<T>>` 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 <T> Observable<Optional<T>>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this)
/**
* Turns a `Flowable<Optional<T>>` 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 <T> Flowable<Optional<T>>.toLazyNullableBinding() = JavaFxSubscriber.toLazyNullableBinding(this)
/**
* Turns a Single into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Single<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
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 <T> Single<T>.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable())
/**
* Turns a `Single<Optional<T>>` 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 <T> Single<Optional<T>>.toLazyNullableBinding() = JavaFxObserver.toLazyNullableBinding(this.toObservable())
/**
* Turns a Maybe into a JavaFX Binding. Calling the Binding's dispose() method will handle the disposal.
*/
fun <T> Maybe<T>.toBinding(actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
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 <T> Maybe<T>.toLazyBinding() = JavaFxObserver.toLazyBinding(this.toObservable())
/**
* Turns a `Maybe<Optional<T>>` 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 <T> Maybe<Optional<T>>.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 <T> Observable<T>.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 <T> Flowable<T>.toLazyBinding(errorHandler: (Throwable) -> Unit) = JavaFxSubscriber.toLazyBinding(this,errorHandler)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservable() = JavaFxObservable.valuesOf(this)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> 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 <T> ObservableValue<T>.toObservable(nullSentinel: T) = JavaFxObservable.valuesOf(this, nullSentinel)
/**
* Create an rx Observable from a javafx ObservableValue, emitting nullable values as Java 8 `Optional` types
* @param <T> the type of the observed value
* @return an Observable emitting `Optional<T>` values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.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 <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.toObservableChanges() = JavaFxObservable.changesOf(this)
/**
* Create an rx Observable from a javafx ObservableValue, and emits changes with old and new non-null value pairs
* @param <T> the type of the observed value
* @return an Observable emitting non-null values as the wrapped ObservableValue changes
*/
fun <T> ObservableValue<T>.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 <T : Event> Node.events(eventType: EventType<T>) = JavaFxObservable.eventsOf(this, eventType)
/**
* Create an rx Observable from a javafx ObservableValue
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T: Event> Scene.events(eventType: EventType<T>) = JavaFxObservable.eventsOf(this,eventType)
/**
* Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs
* @param <T> the type of the observed value
* @return an Observable emitting values as the wrapped ObservableValue changes
*/
fun <T: WindowEvent> Window.events(eventType: EventType<T>) = 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 <T> ObservableList<T>.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 <T> ObservableList<T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableList
* @return An Observable emitting items added to the ObservableList
*/
fun <T> ObservableList<T>.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
* <pre>ObservableList<Person> sourceList = FXCollections.observableArrayList(user -> new javafx.beans.Observable[]{user.age} );</pre>
* @return An Observable emitting items updated in the ObservableList
*/
fun <T> ObservableList<T>.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 <T> ObservableList<T>.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 <T> ObservableList<T>.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 <T,R> ObservableList<T>.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 <T,R> ObservableList<T>.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 <K,T> ObservableMap<K, T>.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 <K,T> ObservableMap<K, T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableMap
* @return An Observable emitting items added to the ObservableMap
*/
fun <K,T> ObservableMap<K, T>.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 <K,T> ObservableMap<K, T>.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 <T> ObservableSet<T>.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 <T> ObservableSet<T>.removals() = JavaFxObservable.removalsOf(this)
/**
* Creates an observable that emits all additions to an ObservableSet
* @return An Observable emitting items added to the ObservableSet
*/
fun <T> ObservableSet<T>.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 <T> ObservableSet<SetChange<T>>.changes() = JavaFxObservable.changesOf(this)
/**
* Emits the response `T` for a given `Dialog<T>`. If no response is provided the Maybe will be empty.
*/
fun <T> Dialog<T>.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 <T> Observable<T>.observeOnFx() = observeOn(JavaFxScheduler.platform())
/**
* Observes the emissions on the JavaFX Thread.
* This is the same as calling Flowable#observeOn(JavaFxScheduler.platform())
*/
fun <T> Flowable<T>.observeOnFx() = observeOn(JavaFxScheduler.platform())
/**
* Observes the emissions on the JavaFX Thread.
* This is the same as calling Single#observeOn(JavaFxScheduler.platform())
*/
fun <T> Single<T>.observeOnFx() = observeOn(JavaFxScheduler.platform())
/**
* Observes the emissions on the JavaFX Thread.
* This is the same as calling Maybe#observeOn(JavaFxScheduler.platform())
*/
fun <T> Maybe<T>.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 <T> Observable<T>.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 <T> Flowable<T>.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform())
/**
* Observes the emissions on the JavaFX Thread.
* This is the same as calling Single#subscribeOnFx(JavaFxScheduler.platform())
*/
fun <T> Single<T>.subscribeOnFx() = subscribeOn(JavaFxScheduler.platform())
/**
* Observes the emissions on the JavaFX Thread.
* This is the same as calling Maybe#subscribeOnFx(JavaFxScheduler.platform())
*/
fun <T> Maybe<T>.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 <T> Observable<T>.doOnNextFx(crossinline onNext: (T) -> Unit): Observable<T> = doOnNext {
Platform.runLater { onNext.invoke(it) }
}
/**
* Performs the provided onNext action on the FX thread
*/
inline fun <T> Flowable<T>.doOnNextFx(crossinline onNext: (T) -> Unit): Flowable<T> = doOnNext {
Platform.runLater { onNext.invoke(it) }
}
/**
* Performs the provided onError action on the FX thread
*/
inline fun <T> Observable<T>.doOnErrorFx(crossinline onError: (Throwable) -> Unit): Observable<T> = doOnError {
Platform.runLater { onError.invoke(it) }
}
/**
* Performs the provided onError action on the FX thread
*/
inline fun <T> Flowable<T>.doOnErrorFx(crossinline onError: (Throwable) -> Unit): Flowable<T> = doOnError {
Platform.runLater { onError.invoke(it) }
}
/**
* Performs the provided onComplete action on the FX thread
*/
inline fun <T> Observable<T>.doOnCompleteFx(crossinline onComplete: () -> Unit): Observable<T> = doOnComplete {
Platform.runLater { onComplete.invoke() }
}
/**
* Performs the provided onComplete action on the FX thread
*/
inline fun <T> Flowable<T>.doOnCompleteFx(crossinline onComplete: () -> Unit): Flowable<T> = doOnComplete {
Platform.runLater { onComplete.invoke() }
}
/**
* Performs the provided onSubscribe action on the FX thread
*/
inline fun <T> Observable<T>.doOnSubscribeFx(crossinline onSubscribe: () -> Unit): Observable<T> = doOnSubscribe {
Platform.runLater { onSubscribe.invoke() }
}
/**
* Performs the provided onSubscribe action on the FX thread
*/
inline fun <T> Flowable<T>.doOnSubscribeFx(crossinline onSubscribe: () -> Unit): Flowable<T> = doOnSubscribe {
Platform.runLater { onSubscribe.invoke() }
}
/**
* Performs the provided onTerminate action on the FX thread
*/
inline fun <T> Observable<T>.doOnTerminateFx(crossinline onTerminate: () -> Unit): Observable<T> = doOnTerminate {
Platform.runLater { onTerminate.invoke() }
}
/**
* Performs the provided onTerminate action on the FX thread
*/
inline fun <T> Flowable<T>.doOnTerminateFx(crossinline onTerminate: () -> Unit): Flowable<T> = doOnTerminate {
Platform.runLater { onTerminate.invoke() }
}
/**
* Performs the provided onDispose action on the FX thread
*/
inline fun <T> Observable<T>.doOnDisposeFx(crossinline onDispose: () -> Unit): Observable<T> = this.doOnDispose {
Platform.runLater { onDispose.invoke() }
}
/**
* Performs the provided onDispose action on the FX thread
*/
inline fun <T> Flowable<T>.doOnCancelFx(crossinline onDispose: () -> Unit): Flowable<T> = this.doOnCancel {
Platform.runLater { onDispose.invoke() }
}
/**
* Executes side effect with the accumulating count of emissions for each onNext() call
*/
fun <T> Observable<T>.doOnNextCount(onNext: (Int) -> Unit): Observable<in T> =
compose(FxObservableTransformers.doOnNextCount(onNext))
/**
* Executes side effect with the accumulating count of emissions for each onNext() call
*/
fun <T> Flowable<T>.doOnNextCount(onNext: (Int) -> Unit): Flowable<in T> =
compose(FxFlowableTransformers.doOnNextCount(onNext))
/**
* Executes side effect with the total count of emissions for the onComplete() call
*/
fun <T> Observable<T>.doOnCompleteCount(onComplete: (Int) -> Unit): Observable<in T> =
compose(FxObservableTransformers.doOnCompleteCount(onComplete))
/**
* Executes side effect with the total count of emissions for the onComplete() call
*/
fun <T> Flowable<T>.doOnCompleteCount(onComplete: (Int) -> Unit): Flowable<in T> =
compose(FxFlowableTransformers.doOnCompleteCount(onComplete))
/**
* Executes side effect with the total count of emissions for an onError() call
*/
fun <T> Observable<T>.doOnErrorCount(onError: (Int) -> Unit): Observable<in T> =
compose(FxObservableTransformers.doOnErrorCount(onError))
/**
* Executes side effect with the total count of emissions for an onError() call
*/
fun <T> Flowable<T>.doOnErrorCount(onError: (Int) -> Unit): Flowable<in T> =
compose(FxFlowableTransformers.doOnErrorCount(onError))
/**
* Executes side effect on FX thread with the accumulating count of emissions for each onNext() call
*/
fun <T> Observable<T>.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 <T> Flowable<T>.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 <T> Observable<T>.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 <T> Flowable<T>.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 <T> Observable<T>.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 <T> Flowable<T>.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 <T> Property<T>.bind(observable: Observable<T>, actionOp: (ObservableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = ObservableBindingSideEffects<T>()
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 <T> Property<T>.bind(flowable: Flowable<T>, actionOp: (FlowableBindingSideEffects<T>.() -> Unit)? = null): Binding<T> {
val transformer = actionOp?.let {
val sideEffects = FlowableBindingSideEffects<T>()
it.invoke(sideEffects)
sideEffects.transformer
}
val binding = (transformer?.let { flowable.compose(it) }?:flowable).toBinding()
bind(binding)
return binding
}
fun <T> Binding<T>.addTo(compositeBinding: CompositeBinding): Binding<T> {
compositeBinding.add(this)
return this
}
operator fun <T> CompositeBinding.plusAssign(binding: Binding<T>) = add(binding)
operator fun CompositeBinding.plusAssign(compositeBinding: CompositeBinding) = add(compositeBinding)
operator fun <T> CompositeBinding.minusAssign(binding: Binding<T>) = remove(binding)
operator fun CompositeBinding.minusAssign(compositeBinding: CompositeBinding) = remove(compositeBinding)
class ObservableBindingSideEffects<T> {
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<T, T> get() = ObservableTransformer<T, T> { obs ->
var withActions: Observable<T> = 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<T> {
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<T, T> get() = FlowableTransformer<T, T> { obs ->
var withActions: Flowable<T> = 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 <T> Optional<T>.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<Int> = 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<Unit>(Exception("Test"))
.toBinding {
onError { counter.incrementAndGet() }
}
assertTrue(counter.get() == 1)
}
}
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
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (72K chars).
[
{
"path": ".gitignore",
"chars": 96,
"preview": ".gradle/\nbuild/\n*.iml\n*.class\n*.prefs\n*.classpath\n.project\n.idea/\ngradle.properties\nsecring.gpg\n"
},
{
"path": "LICENSE.txt",
"chars": 11325,
"preview": "Apache License\n Version 2.0, January 2004\n http://www.apache.org/licens"
},
{
"path": "README.md",
"chars": 10998,
"preview": "\n\n }\n dependencies {\n classpat"
},
{
"path": "gradle/wrapper/gradle-wrapper.properties",
"chars": 231,
"preview": "#Sat Feb 25 20:14:08 CST 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
},
{
"path": "gradlew",
"chars": 4971,
"preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n## Gradle start "
},
{
"path": "gradlew.bat",
"chars": 2314,
"preview": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem "
},
{
"path": "src/main/kotlin/com/github/thomasnield/rxkotlinfx/Nodes.kt",
"chars": 1503,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.Observable\nimport javafx.scene.control.*\n\n/**\n * Returns "
},
{
"path": "src/main/kotlin/com/github/thomasnield/rxkotlinfx/Observables.kt",
"chars": 17089,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.Flowable\nimport io.reactivex.Maybe\nimport io.reactivex.Ob"
},
{
"path": "src/main/kotlin/com/github/thomasnield/rxkotlinfx/Operators.kt",
"chars": 7984,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.*\nimport io.reactivex.rxjavafx.schedulers.JavaFxScheduler"
},
{
"path": "src/main/kotlin/com/github/thomasnield/rxkotlinfx/Subscribers.kt",
"chars": 4046,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.Flowable\nimport io.reactivex.FlowableTransformer\nimport i"
},
{
"path": "src/main/kotlin/com/github/thomasnield/rxkotlinfx/Util.kt",
"chars": 372,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.Observable\nimport java.util.*\n\n@Deprecated(\"Don't use thi"
},
{
"path": "src/test/kotlin/com/github/thomasnield/rxkotlinfx/OperatorsTest.kt",
"chars": 5252,
"preview": "package com.github.thomasnield.rxkotlinfx\n\nimport io.reactivex.Observable\nimport io.reactivex.schedulers.Schedulers\nimpo"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the thomasnield/RxKotlinFX GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (67.1 KB), approximately 16.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.