├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── docs └── rxjavafx-guide.pdf ├── main └── java │ ├── module-info.java │ └── org │ └── pdfsam │ └── rxjavafx │ ├── observables │ └── JavaFxObservable.java │ ├── observers │ ├── BindingObserver.java │ ├── BindingSubscriber.java │ ├── JavaFxObserver.java │ ├── JavaFxSubscriber.java │ └── ObservableListenerHelper.java │ ├── schedulers │ └── JavaFxScheduler.java │ ├── sources │ ├── ActionEventSource.java │ ├── Change.java │ ├── DialogSource.java │ ├── Flag.java │ ├── ListChange.java │ ├── MapChange.java │ ├── NodeEventSource.java │ ├── ObservableListSource.java │ ├── ObservableMapSource.java │ ├── ObservableSetSource.java │ ├── ObservableValueSource.java │ ├── SceneEventSource.java │ ├── SetChange.java │ ├── TimerSource.java │ └── WindowEventSource.java │ ├── subscriptions │ ├── CompositeBinding.java │ └── JavaFxSubscriptions.java │ └── transformers │ ├── FxFlowableTransformers.java │ └── FxObservableTransformers.java └── test └── java └── org └── pdfsam └── rxjavafx ├── RxJavaFXTest.java ├── operators └── OperatorsTest.java ├── schedulers └── JavaFxSchedulerTest.java ├── sources └── JavaFxObservableTest.java └── subscriptions └── BindingTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.rar 19 | *.tar 20 | *.zip 21 | 22 | # Logs and databases # 23 | ###################### 24 | *.log 25 | 26 | # OS generated files # 27 | ###################### 28 | .DS_Store* 29 | ehthumbs.db 30 | Icon? 31 | Thumbs.db 32 | 33 | # Editor Files # 34 | ################ 35 | *~ 36 | *.swp 37 | 38 | # Gradle Files # 39 | ################ 40 | .gradle 41 | .gradletasknamecache 42 | .m2 43 | 44 | # Build output directies 45 | target/ 46 | build/ 47 | 48 | # IntelliJ specific files/directories 49 | out 50 | .idea 51 | *.ipr 52 | *.iws 53 | *.iml 54 | atlassian-ide-plugin.xml 55 | 56 | # Eclipse specific files/directories 57 | .classpath 58 | .project 59 | .settings 60 | .metadata 61 | bin/ 62 | 63 | # NetBeans specific files/directories 64 | .nbattrs 65 | /.nb-gradle/profiles/private/ 66 | .nb-gradle-properties 67 | 68 | # Scala build 69 | *.cache 70 | /.nb-gradle/private/ 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2012 Netflix, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RxJavaFX: JavaFX bindings for RxJava 2 | 3 | This is a fork of the original repository of [RxJavaFX](https://github.com/ReactiveX/RxJavaFX). 4 | 5 | It's a follow up on [this comment](https://github.com/ReactiveX/RxJavaFX/pull/94#issuecomment-908499509) and it's the minimal work needed to make it up and running using [RxJava](https://github.com/ReactiveX/RxJava) version 3.x. As per the comment, the library has been repackaged on a different domain and released to Maven Central. 6 | 7 | This library is released for our needs and to be easily available to our products, you can use it but don't expect any active maintenance. 8 | 9 | A PDF version of the guide written by the original author is available [here](src/docs/rxjavafx-guide.pdf) given the original link is now dead. 10 | 11 | It requires **JDK 11** 12 | 13 | Maven: 14 | 15 | ```xml 16 | 17 | org.pdfsam.rxjava3 18 | rxjavafx 19 | 3.x.y 20 | 21 | ``` 22 | 23 | ## LICENSE 24 | 25 | Licensed under the Apache License, Version 2.0 (the "License"); 26 | you may not use this file except in compliance with the License. 27 | You may obtain a copy of the License at 28 | 29 | 30 | 31 | Unless required by applicable law or agreed to in writing, software 32 | distributed under the License is distributed on an "AS IS" BASIS, 33 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 34 | See the License for the specific language governing permissions and 35 | limitations under the License. 36 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | org.pdfsam.rxjava3 5 | rxjavafx 6 | jar 7 | RxJavaFX repackaged 8 | 3.0.4-SNAPSHOT 9 | 10 | RxJava extensions for JavaFX 11 | https://github.com/torakiki/RxJavaFX 12 | 13 | 14 | GitHub 15 | https://github.com/torakiki/RxJavaFX/issues 16 | 17 | 18 | 19 | 20 | Apache License, Version 2.0 21 | http://www.apache.org/licenses/LICENSE-2.0 22 | repo 23 | ASLv2 24 | 25 | 26 | 27 | 28 | 19 29 | 3.1.8 30 | 5.10.0 31 | 5.5.0 32 | UTF-8 33 | 34 | 35 | 36 | scm:git:git@github.com:torakiki/RxJavaFX.git 37 | scm:git:git@github.com:torakiki/RxJavaFX.git 38 | scm:git:git@github.com:torakiki/RxJavaFX.git 39 | HEAD 40 | 41 | 42 | 43 | 44 | torakiki 45 | Andrea Vacondio 46 | andrea.vacondio@gmail.com 47 | 48 | 49 | 50 | 51 | 52 | sonatype-nexus-snapshots 53 | https://oss.sonatype.org/content/repositories/snapshots 54 | 55 | 56 | pdfsam-ossrh 57 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 58 | 59 | 60 | 61 | 62 | 63 | toolchain 64 | 65 | 66 | env.CI 67 | !true 68 | 69 | 70 | 71 | 72 | 73 | org.apache.maven.plugins 74 | maven-toolchains-plugin 75 | 3.1.0 76 | 77 | 78 | 79 | toolchain 80 | 81 | 82 | 83 | 84 | 85 | 86 | 11 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | release 96 | 97 | 98 | 99 | org.apache.maven.plugins 100 | maven-javadoc-plugin 101 | 3.6.0 102 | 103 | 104 | attach-javadocs 105 | 106 | jar 107 | 108 | 109 | 110 | 111 | 112 | -Xdoclint:none 113 | 114 | 115 | 116 | 117 | org.apache.maven.plugins 118 | maven-release-plugin 119 | 3.0.1 120 | 121 | v@{project.version} 122 | clean install 123 | 124 | 125 | 126 | org.apache.maven.plugins 127 | maven-gpg-plugin 128 | 3.1.0 129 | 130 | 131 | sign-artifacts 132 | verify 133 | 134 | sign 135 | 136 | 137 | 138 | 139 | 140 | org.sonatype.plugins 141 | nexus-staging-maven-plugin 142 | 1.6.13 143 | true 144 | 145 | pdfsam-ossrh 146 | https://oss.sonatype.org/ 147 | true 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | org.apache.maven.plugins 159 | maven-compiler-plugin 160 | 3.11.0 161 | 162 | 11 163 | 164 | 165 | 166 | org.apache.maven.plugins 167 | maven-jar-plugin 168 | 3.3.0 169 | 170 | 171 | 172 | org.pdfsam.rxjavafx 173 | 174 | 175 | 176 | 177 | 178 | org.apache.maven.plugins 179 | maven-source-plugin 180 | 3.3.0 181 | 182 | 183 | attach-sources 184 | 185 | jar-no-fork 186 | 187 | 188 | 189 | 190 | 191 | org.apache.maven.plugins 192 | maven-surefire-plugin 193 | 3.1.2 194 | 195 | 196 | 197 | 198 | 199 | org.openjfx 200 | javafx-controls 201 | ${javafx.version} 202 | 203 | 204 | org.openjfx 205 | javafx-base 206 | ${javafx.version} 207 | 208 | 209 | org.openjfx 210 | javafx-graphics 211 | ${javafx.version} 212 | 213 | 214 | io.reactivex.rxjava3 215 | rxjava 216 | ${rxjava.version} 217 | 218 | 219 | org.mockito 220 | mockito-core 221 | ${mockito.version} 222 | test 223 | 224 | 225 | org.junit.jupiter 226 | junit-jupiter-engine 227 | ${junit.version} 228 | test 229 | 230 | 231 | 232 | 233 | -------------------------------------------------------------------------------- /src/docs/rxjavafx-guide.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/torakiki/RxJavaFX/e248608950549ea846101e0c2a48955244f493a5/src/docs/rxjavafx-guide.pdf -------------------------------------------------------------------------------- /src/main/java/module-info.java: -------------------------------------------------------------------------------- 1 | module org.pdfsam.rxjavafx { 2 | requires transitive io.reactivex.rxjava3; 3 | requires transitive javafx.base; 4 | requires transitive javafx.graphics; 5 | requires transitive javafx.controls; 6 | requires org.reactivestreams; 7 | 8 | exports org.pdfsam.rxjavafx.observables; 9 | exports org.pdfsam.rxjavafx.observers; 10 | exports org.pdfsam.rxjavafx.schedulers; 11 | exports org.pdfsam.rxjavafx.sources; 12 | exports org.pdfsam.rxjavafx.subscriptions; 13 | exports org.pdfsam.rxjavafx.transformers; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observables/JavaFxObservable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.observables; 17 | 18 | 19 | import java.util.Map; 20 | import java.util.Optional; 21 | import java.util.function.Function; 22 | 23 | import org.pdfsam.rxjavafx.sources.ActionEventSource; 24 | import org.pdfsam.rxjavafx.sources.Change; 25 | import org.pdfsam.rxjavafx.sources.DialogSource; 26 | import org.pdfsam.rxjavafx.sources.ListChange; 27 | import org.pdfsam.rxjavafx.sources.MapChange; 28 | import org.pdfsam.rxjavafx.sources.NodeEventSource; 29 | import org.pdfsam.rxjavafx.sources.ObservableListSource; 30 | import org.pdfsam.rxjavafx.sources.ObservableMapSource; 31 | import org.pdfsam.rxjavafx.sources.ObservableSetSource; 32 | import org.pdfsam.rxjavafx.sources.ObservableValueSource; 33 | import org.pdfsam.rxjavafx.sources.SceneEventSource; 34 | import org.pdfsam.rxjavafx.sources.SetChange; 35 | import org.pdfsam.rxjavafx.sources.TimerSource; 36 | import org.pdfsam.rxjavafx.sources.WindowEventSource; 37 | 38 | import io.reactivex.rxjava3.core.Maybe; 39 | import io.reactivex.rxjava3.core.Observable; 40 | import javafx.beans.value.ObservableValue; 41 | import javafx.collections.ObservableList; 42 | import javafx.collections.ObservableMap; 43 | import javafx.collections.ObservableSet; 44 | import javafx.event.ActionEvent; 45 | import javafx.event.Event; 46 | import javafx.event.EventType; 47 | import javafx.scene.Node; 48 | import javafx.scene.Scene; 49 | import javafx.scene.control.ContextMenu; 50 | import javafx.scene.control.Dialog; 51 | import javafx.scene.control.MenuItem; 52 | import javafx.stage.Window; 53 | import javafx.stage.WindowEvent; 54 | import javafx.util.Duration; 55 | 56 | 57 | public enum JavaFxObservable { 58 | ; // no instances 59 | 60 | 61 | /** 62 | * Creates an observable corresponding to JavaFX Node events. 63 | * 64 | * @param node The target of the UI events. 65 | * @param eventType The type of the observed UI events 66 | * @return An Observable of UI events, appropriately typed 67 | */ 68 | public static Observable eventsOf(final Node node, final EventType eventType) { 69 | return NodeEventSource.fromNodeEvents(node, eventType); 70 | } 71 | 72 | /** 73 | * Create an rx Observable from a JavaFX ObservableValue 74 | * 75 | * @param fxObservable the observed ObservableValue 76 | * @param the type of the observed value 77 | * @return an Observable emitting non-null values as the wrapped ObservableValue changes 78 | */ 79 | public static Observable valuesOf(final ObservableValue fxObservable) { 80 | return ObservableValueSource.fromObservableValue(fxObservable); 81 | } 82 | 83 | /** 84 | * Create an rx Observable from a JavaFX ObservableValue 85 | * 86 | * @param fxObservable the observed ObservableValue 87 | * @param nullSentinel the default sentinel value emitted when the observable is null 88 | * @param the type of the observed value 89 | * @return an Observable emitting values as the wrapped ObservableValue changes, null will be replaces with nullSentinel 90 | */ 91 | public static Observable valuesOf(final ObservableValue fxObservable, final T nullSentinel) { 92 | return ObservableValueSource.fromObservableValue(fxObservable, nullSentinel); 93 | } 94 | 95 | /** 96 | * Create an rx Observable from a JavaFX ObservableValue 97 | * 98 | * @param fxObservable the observed ObservableValue 99 | * @param the type of the observed value 100 | * @return an Observable emitting nullable values as the wrapped ObservableValue changes 101 | */ 102 | public static Observable> nullableValuesOf(final ObservableValue fxObservable) { 103 | return ObservableValueSource.fromNullableObservableValue(fxObservable); 104 | } 105 | 106 | /** 107 | * Create an rx Observable from a javafx ObservableValue, and emits changes with old and new value pairs 108 | * 109 | * @param fxObservable the observed ObservableValue 110 | * @param the type of the observed value 111 | * @return an Observable emitting values as the wrapped ObservableValue changes 112 | */ 113 | public static Observable> changesOf(final ObservableValue fxObservable) { 114 | return ObservableValueSource.fromObservableValueChanges(fxObservable); 115 | } 116 | /** 117 | * Create an rx Observable from a javafx ObservableValue, and emits changes with non-null old and new value pairs 118 | * 119 | * @param fxObservable the observed ObservableValue 120 | * @param the type of the observed value 121 | * @return an Observable emitting values as the wrapped ObservableValue changes 122 | */ 123 | public static Observable> nonNullChangesOf(final ObservableValue fxObservable) { 124 | return changesOf(fxObservable).filter(t -> t.getOldVal() != null && t.getNewVal() != null); 125 | } 126 | 127 | /** 128 | * Emits a JavaFX Observable every time it is invalidated. 129 | * @param fxObservable 130 | * @return 131 | */ 132 | public static Observable invalidationsOf(final javafx.beans.Observable fxObservable) { 133 | return ObservableValueSource.fromInvalidations(fxObservable); 134 | } 135 | 136 | 137 | /** 138 | * Creates an observable corresponding to javafx Scene events. 139 | * 140 | * @param scene The target of the UI events. 141 | * @param eventType The type of the observed UI events 142 | * @return An Observable of UI events, appropriately typed 143 | */ 144 | public static Observable eventsOf(final Scene scene, final EventType eventType) { 145 | return SceneEventSource.fromSceneEvents(scene,eventType); 146 | } 147 | 148 | 149 | 150 | /** 151 | * Creates an observable corresponding to javafx Window events. 152 | * 153 | * @param window The target of the UI events. 154 | * @param eventType The type of the observed UI events 155 | * @return An Observable of UI events, appropriately typed 156 | */ 157 | public static Observable eventsOf(final Window window, final EventType eventType) { 158 | return WindowEventSource.fromWindowEvents(window,eventType); 159 | } 160 | 161 | 162 | /** 163 | * Creates an observable corresponding to javafx Node action events. 164 | * 165 | * @param node The target of the ActionEvents 166 | * @return An Observable of UI ActionEvents 167 | */ 168 | public static Observable actionEventsOf(final Node node) { 169 | return ActionEventSource.fromActionEvents(node); 170 | } 171 | 172 | 173 | /** 174 | * Creates an observable corresponding to javafx ContextMenu action events. 175 | * 176 | * @param contextMenu The target of the ActionEvents 177 | * @return An Observable of UI ActionEvents 178 | */ 179 | public static Observable actionEventsOf(final ContextMenu contextMenu) { 180 | return ActionEventSource.fromActionEvents(contextMenu); 181 | } 182 | 183 | 184 | 185 | /** 186 | * Creates an observable corresponding to javafx MenuItem action events. 187 | * 188 | * @param menuItem The target of the ActionEvents 189 | * @return An Observable of UI ActionEvents 190 | */ 191 | public static Observable actionEventsOf(final MenuItem menuItem) { 192 | return ActionEventSource.fromActionEvents(menuItem); 193 | } 194 | 195 | 196 | /** 197 | * Creates an observable that emits an ObservableList every time it is modified 198 | * 199 | * @param source The target ObservableList of the ListChange events 200 | * @return An Observable emitting the ObservableList each time it changes 201 | */ 202 | public static Observable> emitOnChanged(final ObservableList source) { 203 | return ObservableListSource.fromObservableList(source); 204 | } 205 | 206 | 207 | /** 208 | * Creates an observable that emits all additions to an ObservableList 209 | * 210 | * @param source The target ObservableList for the item add events 211 | * @return An Observable emitting items added to the ObservableList 212 | */ 213 | public static Observable additionsOf(final ObservableList source) { 214 | return ObservableListSource.fromObservableListAdds(source); 215 | } 216 | 217 | 218 | 219 | /** 220 | * Creates an observable that emits all removal items from an ObservableList 221 | * 222 | * @param source The target ObservableList for the item removal events 223 | * @return An Observable emitting items removed from the ObservableList 224 | */ 225 | public static Observable removalsOf(final ObservableList source) { 226 | return ObservableListSource.fromObservableListRemovals(source); 227 | } 228 | 229 | 230 | /** 231 | * Creates an observable that emits all updated items from an ObservableList. 232 | * If you declare an ObservableList that listens to one or more properties of each element, 233 | * you can emit the changed items every time these properties are modified 234 | * @param source The target ObservableList for the item update events 235 | * 236 | * @return An Observable emitting items updated in the ObservableList 237 | */ 238 | public static Observable updatesOf(final ObservableList source) { 239 | return ObservableListSource.fromObservableListUpdates(source); 240 | } 241 | 242 | 243 | /** 244 | * Emits all added, removed, and updated items from an ObservableList 245 | * @param source 246 | * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flag 247 | */ 248 | public static Observable> changesOf(final ObservableList source) { 249 | return ObservableListSource.fromObservableListChanges(source); 250 | } 251 | 252 | 253 | /** 254 | * Emits distinctly added and removed items from an ObservableList. 255 | * If dupe items with identical hashcode/equals evaluations are added to an ObservableList, only the first one will fire an ADDED item. 256 | * When the last dupe is removed, only then will it fire a REMOVED item. 257 | * @param source 258 | * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flag 259 | */ 260 | public static Observable> distinctChangesOf(final ObservableList source) { 261 | return ObservableListSource.fromObservableListDistinctChanges(source); 262 | } 263 | 264 | 265 | /** 266 | * Emits distinctly added and removed T items from an ObservableList based on a mapping to an R value. 267 | * 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. 268 | * When the last R dupe is removed, only then will it fire a REMOVED T item. 269 | * @param source 270 | * @return An Observable emitting changed items with an ADDED, REMOVED, or UPDATED flag 271 | */ 272 | public static Observable> distinctChangesOf(final ObservableList source, Function mapper) { 273 | return ObservableListSource.fromObservableListDistinctChanges(source,mapper); 274 | } 275 | 276 | 277 | 278 | /** 279 | * Emits distinctly added and removed mappings to each R item from an ObservableList. 280 | * 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. 281 | * When the last dupe is removed, only then will it fire a REMOVED R item. 282 | * @param source 283 | * @return An Observable emitting changed mapped items with an ADDED, REMOVED, or UPDATED flag 284 | */ 285 | public static Observable> distinctMappingsOf(final ObservableList source, Function mapper) { 286 | return ObservableListSource.fromObservableListDistinctMappings(source,mapper); 287 | } 288 | 289 | 290 | /** 291 | * Creates an observable that emits an ObservableMap every time it is modified 292 | * 293 | * @param source The target ObservableMap of the MapChange events 294 | * @return An Observable emitting the ObservableMap each time it changes 295 | */ 296 | public static Observable> emitOnChanged(final ObservableMap source) { 297 | return ObservableMapSource.fromObservableMap(source); 298 | } 299 | 300 | /** 301 | * Creates an observable that emits all additions to an ObservableMap 302 | * 303 | * @param source The target ObservableMap for the item add events 304 | * @return An Observable emitting Entry items added to the ObservableMap 305 | */ 306 | public static Observable> additionsOf(final ObservableMap source) { 307 | return ObservableMapSource.fromObservableMapAdds(source); 308 | } 309 | 310 | 311 | /** 312 | * Creates an observable that emits all removal items from an ObservableMap 313 | * 314 | * @param source The target ObservableMap for the item removal events 315 | * @return An Observable emitting items removed Entry items from the ObservableMap 316 | */ 317 | public static Observable> removalsOf(final ObservableMap source) { 318 | return ObservableMapSource.fromObservableMapRemovals(source); 319 | } 320 | 321 | 322 | 323 | /** 324 | * Emits all added and removed items (including swaps) from an ObservableMap 325 | * @param source 326 | * @return An Observable emitting changed entries with an ADDED or REMOVED flag 327 | */ 328 | public static Observable> changesOf(final ObservableMap source) { 329 | return ObservableMapSource.fromObservableMapChanges(source); 330 | } 331 | 332 | 333 | /** 334 | * Creates an observable that emits an ObservableSet every time it is modified 335 | * 336 | * @param source The target ObservableSet of the SetChange events 337 | * @return An Observable emitting the ObservableSet each time it changes 338 | */ 339 | public static Observable> emitOnChanged(final ObservableSet source) { 340 | return ObservableSetSource.fromObservableSet(source); 341 | } 342 | 343 | 344 | /** 345 | * Creates an observable that emits all additions to an ObservableSet 346 | * 347 | * @param source The target ObservableSet for the item add events 348 | * @return An Observable emitting items added to the ObservableSet 349 | */ 350 | public static Observable additionsOf(final ObservableSet source) { 351 | return ObservableSetSource.fromObservableSetAdds(source); 352 | } 353 | 354 | 355 | 356 | /** 357 | * Creates an observable that emits all removal items from an ObservableSet 358 | * 359 | * @param source The target ObservableSet for the item removal events 360 | * @return An Observable emitting items removed items from the ObservableSet 361 | */ 362 | public static Observable removalsOf(final ObservableSet source) { 363 | return ObservableSetSource.fromObservableSetRemovals(source); 364 | } 365 | 366 | 367 | /** 368 | * Emits all added and removed items (including swaps) from an ObservableSet 369 | * @param source 370 | * @return An Observable emitting changed entries with an ADDED or REMOVED flag 371 | */ 372 | public static Observable> changesOf(final ObservableSet source) { 373 | return ObservableSetSource.fromObservableSetChanges(source); 374 | } 375 | 376 | /** 377 | * Returns an Observable that emits a 0L and ever increasing numbers after each duration of time thereafter 378 | */ 379 | public static Observable interval(final Duration duration) { 380 | return TimerSource.interval(duration); 381 | } 382 | 383 | /** 384 | * Returns a Maybe that emits the T response of a Dialog. If no response was given then the Maybe will be empty. 385 | */ 386 | public static Maybe fromDialog(Dialog dialog) { 387 | return DialogSource.fromDialogSource(dialog); 388 | } 389 | } 390 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observers/BindingObserver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.observers; 17 | 18 | import io.reactivex.rxjava3.core.Observer; 19 | import io.reactivex.rxjava3.disposables.Disposable; 20 | import io.reactivex.rxjava3.functions.Consumer; 21 | import io.reactivex.rxjava3.functions.Function; 22 | import io.reactivex.rxjava3.observables.ConnectableObservable; 23 | import javafx.beans.binding.Binding; 24 | import javafx.beans.value.ObservableValue; 25 | import javafx.collections.ObservableList; 26 | 27 | final class BindingObserver extends ObservableListenerHelper implements Observer, ObservableValue, Binding { 28 | 29 | private final Function unmaskingFunction; 30 | private final Consumer onError; 31 | private final ConnectableObservable obs; 32 | private boolean connected = false; 33 | private Disposable disposable; 34 | private S value; 35 | 36 | BindingObserver(Function unmaskingFunction, Consumer onError) { 37 | this.unmaskingFunction = unmaskingFunction; 38 | this.onError = onError; 39 | this.obs = null; 40 | } 41 | 42 | BindingObserver(Function unmaskingFunction, ConnectableObservable obs, Consumer onError) { 43 | this.unmaskingFunction = unmaskingFunction; 44 | this.onError = onError; 45 | this.obs = obs; 46 | } 47 | 48 | @Override 49 | public void onSubscribe(Disposable d) { 50 | this.disposable = d; 51 | } 52 | 53 | @Override 54 | public void onComplete() { 55 | //do nothing 56 | } 57 | 58 | @Override 59 | public void onError(Throwable e) { 60 | try { 61 | onError.accept(e); 62 | } catch (Throwable e1) { 63 | e1.printStackTrace(); 64 | } 65 | } 66 | 67 | @Override 68 | public void onNext(T t) { 69 | try { 70 | value = unmaskingFunction.apply(t); 71 | fireChange(); 72 | } catch (Throwable e) { 73 | onError(e); 74 | } 75 | } 76 | 77 | @Override 78 | public S getValue() { 79 | if (!connected && obs != null) { 80 | obs.connect(); 81 | connected = true; 82 | } 83 | return value; 84 | } 85 | 86 | @Override 87 | public boolean isValid() { 88 | return true; 89 | } 90 | 91 | @Override 92 | public void invalidate() { 93 | //does nothing 94 | } 95 | 96 | @Override 97 | public ObservableList getDependencies() { 98 | throw new UnsupportedOperationException(); 99 | } 100 | 101 | @Override 102 | public void dispose() { 103 | if (disposable != null) { 104 | disposable.dispose(); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observers/BindingSubscriber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.observers; 17 | 18 | import org.reactivestreams.Subscriber; 19 | import org.reactivestreams.Subscription; 20 | 21 | import io.reactivex.rxjava3.flowables.ConnectableFlowable; 22 | import io.reactivex.rxjava3.functions.Consumer; 23 | import io.reactivex.rxjava3.functions.Function; 24 | import javafx.beans.binding.Binding; 25 | import javafx.beans.value.ObservableValue; 26 | import javafx.collections.ObservableList; 27 | 28 | final class BindingSubscriber extends ObservableListenerHelper implements Subscriber, ObservableValue, Binding { 29 | 30 | private final Function unmaskingFunction; 31 | private final Consumer onError; 32 | private final ConnectableFlowable obs; 33 | private boolean connected = false; 34 | private Subscription subscription; 35 | private S value; 36 | 37 | BindingSubscriber(Function unmaskingFunction, Consumer onError) { 38 | this.unmaskingFunction = unmaskingFunction; 39 | this.onError = onError; 40 | this.obs = null; 41 | } 42 | 43 | BindingSubscriber(Function unmaskingFunction, ConnectableFlowable obs, Consumer onError) { 44 | this.unmaskingFunction = unmaskingFunction; 45 | this.onError = onError; 46 | this.obs = obs; 47 | } 48 | 49 | @Override 50 | public void onSubscribe(Subscription s) { 51 | this.subscription = s; 52 | this.subscription.request(Long.MAX_VALUE); 53 | } 54 | 55 | @Override 56 | public void onComplete() { 57 | //do nothing 58 | } 59 | 60 | @Override 61 | public void onError(Throwable e) { 62 | try { 63 | onError.accept(e); 64 | } catch (Throwable e1) { 65 | e1.printStackTrace(); 66 | } 67 | } 68 | 69 | @Override 70 | public void onNext(T t) { 71 | try { 72 | value = unmaskingFunction.apply(t); 73 | fireChange(); 74 | } catch (Throwable e) { 75 | onError(e); 76 | } 77 | } 78 | 79 | @Override 80 | public S getValue() { 81 | if (!connected && obs != null) { 82 | obs.connect(); 83 | connected = true; 84 | } 85 | return value; 86 | } 87 | 88 | @Override 89 | public boolean isValid() { 90 | return true; 91 | } 92 | 93 | @Override 94 | public void invalidate() { 95 | //does nothing 96 | } 97 | 98 | @Override 99 | public ObservableList getDependencies() { 100 | throw new UnsupportedOperationException(); 101 | } 102 | 103 | @Override 104 | public void dispose() { 105 | if (subscription != null) { 106 | subscription.cancel(); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observers/JavaFxObserver.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.observers; 17 | 18 | import java.util.Optional; 19 | 20 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 21 | 22 | import io.reactivex.rxjava3.core.Observable; 23 | import io.reactivex.rxjava3.functions.Consumer; 24 | import io.reactivex.rxjava3.observables.ConnectableObservable; 25 | import io.reactivex.rxjava3.plugins.RxJavaPlugins; 26 | import javafx.beans.binding.Binding; 27 | import javafx.beans.value.ObservableValue; 28 | 29 | public enum JavaFxObserver { 30 | ;//no instances 31 | 32 | /** 33 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 34 | */ 35 | public static Binding toBinding(Observable obs) { 36 | return toBinding(obs, JavaFxObserver::onError); 37 | } 38 | 39 | /** 40 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 41 | */ 42 | public static Binding toBinding(Observable obs, Consumer onErrorAction) { 43 | BindingObserver bindingObserver = new BindingObserver<>(t -> t, onErrorAction); 44 | obs.subscribe(bindingObserver); 45 | return bindingObserver; 46 | } 47 | 48 | /** 49 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 50 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 51 | */ 52 | public static Binding toNullBinding(Observable obs, T nullSentinel) { 53 | return toNullBinding(obs, nullSentinel, JavaFxObserver::onError); 54 | } 55 | 56 | /** 57 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 58 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 59 | */ 60 | public static Binding toNullBinding(Observable obs, T nullSentinel, Consumer onErrorAction) { 61 | if (nullSentinel == null) { 62 | throw new NullPointerException("The null value sentinel must not be null."); 63 | } 64 | BindingObserver bindingObserver = new BindingObserver<>(t -> t == nullSentinel ? null : t, onErrorAction); 65 | obs.subscribe(bindingObserver); 66 | return bindingObserver; 67 | } 68 | 69 | /** 70 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 71 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 72 | */ 73 | public static Binding toNullableBinding(Observable> obs) { 74 | return toNullableBinding(obs, JavaFxObserver::onError); 75 | } 76 | 77 | /** 78 | * Turns an Observable into an eager JavaFX Binding that subscribes immediately to the Observable. Calling the Binding's dispose() method will handle the unsubscription. 79 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 80 | */ 81 | public static Binding toNullableBinding(Observable> obs, Consumer onErrorAction) { 82 | BindingObserver, T> bindingObserver = new BindingObserver<>(o -> o.orElse(null), onErrorAction); 83 | obs.subscribe(bindingObserver); 84 | return bindingObserver; 85 | } 86 | 87 | /** 88 | * Turns an Observable into an lazy JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 89 | */ 90 | public static Binding toLazyBinding(Observable obs) { 91 | return toLazyBinding(obs, JavaFxObserver::onError); 92 | } 93 | 94 | /** 95 | * Turns an Observable into an eager JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 96 | */ 97 | public static Binding toLazyBinding(Observable obs, Consumer onErrorAction) { 98 | ConnectableObservable published = obs.publish(); 99 | BindingObserver bindingObserver = new BindingObserver<>(t -> t, published, onErrorAction); 100 | published.subscribe(bindingObserver); 101 | return bindingObserver; 102 | } 103 | 104 | /** 105 | * Turns an Observable into an eager JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 106 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 107 | */ 108 | public static Binding toLazyNullBinding(Observable obs, T nullSentinel) { 109 | return toLazyNullBinding(obs, nullSentinel, JavaFxObserver::onError); 110 | } 111 | 112 | /** 113 | * Turns an Observable into an eager JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 114 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 115 | */ 116 | public static Binding toLazyNullBinding(Observable obs, T nullSentinel, Consumer onErrorAction) { 117 | if (nullSentinel == null) { 118 | throw new NullPointerException("The null value sentinel must not be null."); 119 | } 120 | ConnectableObservable published = obs.publish(); 121 | BindingObserver bindingObserver = new BindingObserver<>(t -> t == nullSentinel ? null : t, published, onErrorAction); 122 | published.subscribe(bindingObserver); 123 | return bindingObserver; 124 | } 125 | 126 | /** 127 | * Turns an Observable into an lazy JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 128 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 129 | */ 130 | public static Binding toLazyNullableBinding(Observable> obs) { 131 | return toLazyNullableBinding(obs, JavaFxObserver::onError); 132 | } 133 | 134 | /** 135 | * Turns an Observable into an lazy JavaFX Binding that subscribes to the Observable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 136 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 137 | */ 138 | public static Binding toLazyNullableBinding(Observable> obs, Consumer onErrorAction) { 139 | ConnectableObservable> published = obs.publish(); 140 | BindingObserver, T> bindingObserver = new BindingObserver<>(o -> o.orElse(null), published, onErrorAction); 141 | published.subscribe(bindingObserver); 142 | return bindingObserver; 143 | } 144 | 145 | private static void onError(Throwable t) { 146 | RxJavaPlugins.onError(t); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observers/JavaFxSubscriber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.observers; 17 | 18 | import java.util.Optional; 19 | 20 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 21 | 22 | import io.reactivex.rxjava3.core.Flowable; 23 | import io.reactivex.rxjava3.flowables.ConnectableFlowable; 24 | import io.reactivex.rxjava3.functions.Consumer; 25 | import io.reactivex.rxjava3.plugins.RxJavaPlugins; 26 | import javafx.beans.binding.Binding; 27 | import javafx.beans.value.ObservableValue; 28 | 29 | public enum JavaFxSubscriber { 30 | ;//no instances 31 | 32 | /** 33 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 34 | */ 35 | public static Binding toBinding(Flowable flowable) { 36 | return toBinding(flowable, JavaFxSubscriber::onError); 37 | } 38 | 39 | /** 40 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 41 | */ 42 | public static Binding toBinding(Flowable flowable, Consumer onErrorAction) { 43 | BindingSubscriber bindingSubscriber = new BindingSubscriber<>(t -> t, onErrorAction); 44 | flowable.subscribe(bindingSubscriber); 45 | return bindingSubscriber; 46 | } 47 | 48 | /** 49 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 50 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 51 | */ 52 | public static Binding toNullBinding(Flowable flowable, T nullSentinel) { 53 | return toNullBinding(flowable, nullSentinel, JavaFxSubscriber::onError); 54 | } 55 | 56 | /** 57 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 58 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 59 | */ 60 | public static Binding toNullBinding(Flowable flowable, T nullSentinel, Consumer onErrorAction) { 61 | if (nullSentinel == null) { 62 | throw new NullPointerException("The null value sentinel must not be null."); 63 | } 64 | BindingSubscriber bindingSubscriber = new BindingSubscriber<>(t -> t == nullSentinel ? null : t, onErrorAction); 65 | flowable.subscribe(bindingSubscriber); 66 | return bindingSubscriber; 67 | } 68 | 69 | /** 70 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 71 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 72 | */ 73 | public static Binding toNullableBinding(Flowable> flowable) { 74 | return toNullableBinding(flowable, JavaFxSubscriber::onError); 75 | } 76 | 77 | /** 78 | * Turns an Flowable into an eager JavaFX Binding that subscribes immediately to the Flowable. Calling the Binding's dispose() method will handle the unsubscription. 79 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 80 | */ 81 | public static Binding toNullableBinding(Flowable> flowable, Consumer onErrorAction) { 82 | BindingSubscriber, T> bindingSubscriber = new BindingSubscriber<>(o -> o.orElse(null), onErrorAction); 83 | flowable.subscribe(bindingSubscriber); 84 | return bindingSubscriber; 85 | } 86 | 87 | /** 88 | * Turns an Flowable into an lazy JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 89 | */ 90 | public static Binding toLazyBinding(Flowable flowable) { 91 | return toLazyBinding(flowable, JavaFxSubscriber::onError); 92 | } 93 | 94 | /** 95 | * Turns an Flowable into an eager JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 96 | */ 97 | public static Binding toLazyBinding(Flowable flowable, Consumer onErrorAction) { 98 | ConnectableFlowable published = flowable.publish(); 99 | BindingSubscriber bindingSubscriber = new BindingSubscriber<>(t -> t, published, onErrorAction); 100 | published.subscribe(bindingSubscriber); 101 | return bindingSubscriber; 102 | } 103 | 104 | /** 105 | * Turns an Flowable into an eager JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 106 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 107 | */ 108 | public static Binding toLazyNullBinding(Flowable flowable, T nullSentinel) { 109 | return toLazyNullBinding(flowable, nullSentinel, JavaFxSubscriber::onError); 110 | } 111 | 112 | /** 113 | * Turns an Flowable into an eager JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 114 | * This variant unmasks a nullable value as in {@link JavaFxObservable#valuesOf(ObservableValue, Object)} and emits null when the sentinel is encountered. 115 | */ 116 | public static Binding toLazyNullBinding(Flowable flowable, T nullSentinel, Consumer onErrorAction) { 117 | if (nullSentinel == null) { 118 | throw new NullPointerException("The null value sentinel must not be null."); 119 | } 120 | ConnectableFlowable published = flowable.publish(); 121 | BindingSubscriber bindingSubscriber = new BindingSubscriber<>(t -> t == nullSentinel ? null : t, published, onErrorAction); 122 | published.subscribe(bindingSubscriber); 123 | return bindingSubscriber; 124 | } 125 | 126 | /** 127 | * Turns an Flowable into an lazy JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 128 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 129 | */ 130 | public static Binding toLazyNullableBinding(Flowable> flowable) { 131 | return toLazyNullableBinding(flowable, JavaFxSubscriber::onError); 132 | } 133 | 134 | /** 135 | * Turns an Flowable into an lazy JavaFX Binding that subscribes to the Flowable when its getValue() is called. Calling the Binding's dispose() method will handle the unsubscription. 136 | * This variant unmasks a nullable value as in {@link JavaFxObservable#nullableValuesOf(ObservableValue)} and emits null when the value is not present. 137 | */ 138 | public static Binding toLazyNullableBinding(Flowable> flowable, Consumer onErrorAction) { 139 | ConnectableFlowable> published = flowable.publish(); 140 | BindingSubscriber, T> bindingSubscriber = new BindingSubscriber<>(o -> o.orElse(null), published, onErrorAction); 141 | published.subscribe(bindingSubscriber); 142 | return bindingSubscriber; 143 | } 144 | 145 | private static void onError(Throwable t) { 146 | RxJavaPlugins.onError(t); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/observers/ObservableListenerHelper.java: -------------------------------------------------------------------------------- 1 | package org.pdfsam.rxjavafx.observers; 2 | 3 | import java.util.Arrays; 4 | import java.util.Objects; 5 | 6 | import javafx.beans.InvalidationListener; 7 | import javafx.beans.value.ChangeListener; 8 | import javafx.beans.value.ObservableValue; 9 | 10 | public abstract class ObservableListenerHelper implements ObservableValue { 11 | private boolean sentinel; 12 | private int invalidationSize = 0; 13 | private int size = 0; 14 | private Object listener = null; 15 | private T value = null; 16 | 17 | /** 18 | * {@inheritDoc} 19 | */ 20 | @Override 21 | public void addListener(InvalidationListener listener) { 22 | Objects.requireNonNull(listener); 23 | if (size == 0) { 24 | sentinel = false; 25 | invalidationSize = 1; 26 | this.listener = listener; 27 | } else if (size == 1) { 28 | sentinel = false; 29 | if (invalidationSize == 1) { 30 | invalidationSize = 2; 31 | this.listener = new Object[]{this.listener, listener}; 32 | } else { 33 | invalidationSize = 1; 34 | this.listener = new Object[]{listener, this.listener}; 35 | } 36 | } else { 37 | Object[] l = (Object[]) this.listener; 38 | 39 | if (l.length <= size + 1 || sentinel) { 40 | sentinel = false; 41 | l = Arrays.copyOf(l, l.length * 3 / 2 + 1); 42 | this.listener = l; 43 | } 44 | if (size > invalidationSize) { 45 | System.arraycopy(l, invalidationSize, l, invalidationSize + 1, size - invalidationSize); 46 | } 47 | l[invalidationSize] = listener; 48 | invalidationSize++; 49 | } 50 | size++; 51 | } 52 | 53 | /** 54 | * {@inheritDoc} 55 | */ 56 | @Override 57 | public void removeListener(InvalidationListener listener) { 58 | Objects.requireNonNull(listener); 59 | if (0 < invalidationSize) { 60 | if (size == 1) { 61 | if (invalidationSize == 1 && this.listener.equals(listener)) { 62 | sentinel = false; 63 | this.listener = null; 64 | invalidationSize--; 65 | size--; 66 | } 67 | } else if (size == 2) { 68 | Object[] l = (Object[]) this.listener; 69 | if (listener.equals(l[0])) { 70 | sentinel = false; 71 | invalidationSize--; 72 | size--; 73 | this.listener = l[1]; 74 | } else if (invalidationSize == 2 && listener.equals(l[1])) { 75 | sentinel = false; 76 | invalidationSize--; 77 | size--; 78 | this.listener = l[0]; 79 | } 80 | } else { 81 | Object[] l = (Object[]) this.listener; 82 | 83 | for (int i = 0; i < invalidationSize; i++) { 84 | if (listener.equals(l[i])) { 85 | if (sentinel) { 86 | sentinel = false; 87 | l = Arrays.copyOf(l, l.length); 88 | this.listener = l; 89 | } 90 | if (i + 1 < size) { 91 | System.arraycopy(l, i + 1, l, i, size - i - 1); 92 | } else { 93 | l[i] = null; 94 | } 95 | invalidationSize--; 96 | size--; 97 | break; 98 | } 99 | } 100 | } 101 | } 102 | } 103 | 104 | /** 105 | * {@inheritDoc} 106 | */ 107 | @Override 108 | public void addListener(ChangeListener listener) { 109 | Objects.requireNonNull(listener); 110 | if (size == 0) { 111 | sentinel = false; 112 | this.listener = listener; 113 | this.value = getValue(); 114 | } else if (size == 1) { 115 | sentinel = false; 116 | this.listener = new Object[]{this.listener, listener}; 117 | } else { 118 | Object[] l = (Object[]) this.listener; 119 | if (l.length <= size + 1) { // test for sentinel not required as we put the new listener behind this.size, thus it won't be fired 120 | sentinel = false; 121 | l = Arrays.copyOf(l, l.length * 3 / 2 + 1); 122 | this.listener = l; 123 | } 124 | l[size] = listener; 125 | } 126 | if (invalidationSize == size) { 127 | this.value = getValue(); 128 | } 129 | size++; 130 | } 131 | 132 | /** 133 | * {@inheritDoc} 134 | */ 135 | @Override 136 | public void removeListener(ChangeListener listener) { 137 | Objects.requireNonNull(listener); 138 | if (invalidationSize < size) { 139 | if (size == 1) { 140 | sentinel = false; 141 | size--; 142 | this.listener = null; 143 | this.value = null; 144 | } else if (size == 2) { 145 | Object[] l = (Object[]) this.listener; 146 | if (listener.equals(l[1])) { 147 | sentinel = false; 148 | size--; 149 | this.listener = l[0]; 150 | if (invalidationSize == 1) { 151 | this.value = null; 152 | } 153 | } else if (invalidationSize == 0 && listener.equals(l[1])) { 154 | sentinel = false; 155 | size--; 156 | this.listener = l[1]; 157 | } 158 | } else { 159 | Object[] l = (Object[]) this.listener; 160 | 161 | for (int i = invalidationSize; i < size; i++) { 162 | if (listener.equals(l[i])) { 163 | if (sentinel) { 164 | sentinel = false; 165 | l = Arrays.copyOf(l, l.length); 166 | this.listener = l; 167 | } 168 | if (i + 1 < size) { 169 | System.arraycopy(l, i + 1, l, i, size - i - 1); 170 | } else { 171 | l[i] = null; 172 | } 173 | size--; 174 | if (size == invalidationSize) { 175 | this.value = null; 176 | } 177 | break; 178 | } 179 | } 180 | } 181 | } 182 | } 183 | 184 | protected void fireChange() { 185 | Object listener = this.listener; 186 | int invalidationSize = this.invalidationSize; 187 | int size = this.size; 188 | try { 189 | sentinel = true; 190 | 191 | if (size == 1) { 192 | if (invalidationSize == 1) { 193 | try { 194 | ((InvalidationListener) listener).invalidated(this); 195 | } catch (Exception e) { 196 | Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); 197 | } 198 | } else { 199 | T oldValue = this.value; 200 | this.value = getValue(); 201 | try { 202 | ((ChangeListener) listener).changed(this, oldValue, this.value); 203 | } catch (Exception e) { 204 | Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); 205 | } 206 | } 207 | } else if (size > 0) { 208 | Object[] l = (Object[]) listener; 209 | 210 | for (int i = 0; i < invalidationSize; i++) { 211 | try { 212 | ((InvalidationListener) l[i]).invalidated(this); 213 | } catch (Exception e) { 214 | Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); 215 | } 216 | } 217 | 218 | if (invalidationSize < size) { 219 | T oldValue = this.value; 220 | this.value = getValue(); 221 | for (int i = invalidationSize; i < size; i++) { 222 | try { 223 | ((ChangeListener) l[i]).changed(this, oldValue, this.value); 224 | } catch (Exception e) { 225 | Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e); 226 | } 227 | } 228 | } 229 | } 230 | } finally { 231 | sentinel = false; 232 | } 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/schedulers/JavaFxScheduler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.schedulers; 17 | 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.atomic.AtomicReference; 20 | 21 | import io.reactivex.rxjava3.core.Scheduler; 22 | import io.reactivex.rxjava3.disposables.Disposable; 23 | import javafx.animation.KeyFrame; 24 | import javafx.animation.Timeline; 25 | import javafx.application.Platform; 26 | import javafx.util.Duration; 27 | 28 | /** 29 | * Executes work on the JavaFx UI thread. 30 | * This scheduler should only be used with actions that execute quickly. 31 | */ 32 | public final class JavaFxScheduler extends Scheduler { 33 | private static final JavaFxScheduler INSTANCE = new JavaFxScheduler(); 34 | 35 | /* package for unit test */JavaFxScheduler() { 36 | } 37 | 38 | public static JavaFxScheduler platform() { 39 | return INSTANCE; 40 | } 41 | 42 | private static void assertThatTheDelayIsValidForTheJavaFxTimer(long delay) { 43 | if (delay < 0 || delay > Integer.MAX_VALUE) { 44 | throw new IllegalArgumentException(String.format("The JavaFx timer only accepts non-negative delays up to %d milliseconds.", Integer.MAX_VALUE)); 45 | } 46 | } 47 | 48 | @Override 49 | public Worker createWorker() { 50 | return new JavaFxWorker(); 51 | } 52 | 53 | /** 54 | * A Worker implementation which manages a queue of QueuedRunnable for execution on the Java FX Application thread 55 | * For a simpler implementation the queue always contains at least one element. 56 | * {@link #head} is the element, which is in execution or was last executed 57 | * {@link #tail} is an atomic reference to the last element in the queue, or null when the worker was disposed 58 | * Recursive actions are not preferred and inserted at the tail of the queue as any other action would be 59 | * The Worker will only schedule a single job with {@link Platform#runLater(Runnable)} for when the queue was previously empty 60 | */ 61 | private static class JavaFxWorker extends Worker implements Runnable { 62 | private volatile QueuedRunnable head = new QueuedRunnable(null); /// only advanced in run(), initialised with a starter element 63 | private final AtomicReference tail = new AtomicReference<>(head); /// points to the last element, null when disposed 64 | 65 | private static class QueuedRunnable extends AtomicReference implements Disposable, Runnable { 66 | private volatile Runnable action; 67 | 68 | private QueuedRunnable(Runnable action) { 69 | this.action = action; 70 | } 71 | 72 | @Override 73 | public void dispose() { 74 | action = null; 75 | } 76 | 77 | @Override 78 | public boolean isDisposed() { 79 | return action == null; 80 | } 81 | 82 | @Override 83 | public void run() { 84 | Runnable action = this.action; 85 | if (action != null) { 86 | action.run(); 87 | } 88 | this.action = null; 89 | } 90 | } 91 | 92 | @Override 93 | public void dispose() { 94 | tail.set(null); 95 | QueuedRunnable qr = this.head; 96 | while (qr != null) { 97 | qr.dispose(); 98 | qr = qr.getAndSet(null); 99 | } 100 | } 101 | 102 | @Override 103 | public boolean isDisposed() { 104 | return tail.get() == null; 105 | } 106 | 107 | @Override 108 | public Disposable schedule(final Runnable action, long delayTime, TimeUnit unit) { 109 | long delay = Math.max(0, unit.toMillis(delayTime)); 110 | assertThatTheDelayIsValidForTheJavaFxTimer(delay); 111 | 112 | final QueuedRunnable queuedRunnable = new QueuedRunnable(action); 113 | if (delay == 0) { // delay is too small for the java fx timer, schedule it without delay 114 | return schedule(queuedRunnable); 115 | } 116 | 117 | final Timeline timer = new Timeline(new KeyFrame(Duration.millis(delay), event -> schedule(queuedRunnable))); 118 | timer.play(); 119 | 120 | return Disposable.fromRunnable(() -> { 121 | queuedRunnable.dispose(); 122 | timer.stop(); 123 | }); 124 | } 125 | 126 | @Override 127 | public Disposable schedule(final Runnable action) { 128 | if (isDisposed()) { 129 | return Disposable.disposed(); 130 | } 131 | 132 | final QueuedRunnable queuedRunnable = action instanceof QueuedRunnable ? (QueuedRunnable) action : new QueuedRunnable(action); 133 | 134 | QueuedRunnable tailPivot; 135 | do { 136 | tailPivot = tail.get(); 137 | } while (tailPivot != null && !tailPivot.compareAndSet(null, queuedRunnable)); 138 | 139 | if (tailPivot == null) { 140 | queuedRunnable.dispose(); 141 | } else { 142 | tail.compareAndSet(tailPivot, queuedRunnable); // can only fail with a concurrent dispose and we don't want to override the disposed value 143 | if (tailPivot == head) { 144 | if (Platform.isFxApplicationThread()) { 145 | run(); 146 | } else { 147 | Platform.runLater(this); 148 | } 149 | } 150 | } 151 | return queuedRunnable; 152 | } 153 | 154 | @Override 155 | public void run() { 156 | for (QueuedRunnable qr = head.get(); qr != null; qr = qr.get()) { 157 | qr.run(); 158 | head = qr; 159 | } 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ActionEventSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 19 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 20 | 21 | import io.reactivex.rxjava3.core.Observable; 22 | import io.reactivex.rxjava3.core.ObservableEmitter; 23 | import javafx.event.ActionEvent; 24 | import javafx.event.EventHandler; 25 | import javafx.scene.Node; 26 | import javafx.scene.control.ContextMenu; 27 | import javafx.scene.control.MenuItem; 28 | 29 | public final class ActionEventSource { 30 | private ActionEventSource() {} 31 | 32 | public static Observable fromActionEvents(final Node node) { 33 | return NodeEventSource.fromNodeEvents(node, ActionEvent.ACTION); 34 | } 35 | public static Observable fromActionEvents(final ContextMenu source) { 36 | 37 | return Observable.create((ObservableEmitter subscriber) -> { 38 | final EventHandler handler = subscriber::onNext; 39 | 40 | source.addEventHandler(ActionEvent.ANY, handler); 41 | 42 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeEventHandler(ActionEvent.ANY, handler))); 43 | }).subscribeOn(JavaFxScheduler.platform()); 44 | } 45 | public static Observable fromActionEvents(final MenuItem source) { 46 | return Observable.create((ObservableEmitter subscriber) -> { 47 | final EventHandler handler = subscriber::onNext; 48 | 49 | source.addEventHandler(ActionEvent.ANY, handler); 50 | 51 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeEventHandler(ActionEvent.ANY, handler))); 52 | }).subscribeOn(JavaFxScheduler.platform()); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/Change.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.Objects; 19 | 20 | public final class Change { 21 | private final T oldVal; 22 | private final T newVal; 23 | 24 | public Change(T oldVal, T newVal) { 25 | this.oldVal = oldVal; 26 | this.newVal = newVal; 27 | } 28 | public T getOldVal() { 29 | return oldVal; 30 | } 31 | public T getNewVal() { 32 | return newVal; 33 | } 34 | 35 | @Override 36 | public boolean equals(Object o) { 37 | if (this == o) return true; 38 | if (o == null || getClass() != o.getClass()) return false; 39 | Change change = (Change) o; 40 | return Objects.equals(oldVal, change.oldVal) && 41 | Objects.equals(newVal, change.newVal); 42 | } 43 | 44 | @Override 45 | public int hashCode() { 46 | return Objects.hash(oldVal, newVal); 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "Change{" + 52 | "oldVal=" + oldVal + 53 | ", newVal=" + newVal + 54 | '}'; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/DialogSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.Optional; 19 | 20 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 21 | 22 | import io.reactivex.rxjava3.core.Maybe; 23 | import io.reactivex.rxjava3.core.Single; 24 | import javafx.scene.control.Dialog; 25 | 26 | public final class DialogSource { 27 | private DialogSource() {} 28 | 29 | public static Maybe fromDialogSource(final Dialog dialog) { 30 | return Single.fromCallable(dialog::showAndWait) 31 | .subscribeOn(JavaFxScheduler.platform()) 32 | .filter(Optional::isPresent) 33 | .map(Optional::get); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/Flag.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | public enum Flag { 19 | ADDED, 20 | REMOVED, 21 | UPDATED; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ListChange.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | /** 19 | * Holds an ADDED, REMOVED, or UPDATED flag with the associated value 20 | * @param 21 | */ 22 | public final class ListChange { 23 | private final T value; 24 | private final Flag flag; 25 | 26 | private ListChange(T value, Flag flag) { 27 | this.value = value; 28 | this.flag = flag; 29 | } 30 | public static ListChange of(T value, Flag flag) { 31 | return new ListChange<>(value, flag); 32 | } 33 | public T getValue() { 34 | return value; 35 | } 36 | public Flag getFlag() { 37 | return flag; 38 | } 39 | @Override 40 | public String toString() { 41 | return flag + " " + value; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/MapChange.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | public final class MapChange { 19 | private final K key; 20 | private final T value; 21 | private final Flag flag; 22 | 23 | MapChange(K key, T value, Flag flag) { 24 | this.key = key; 25 | this.value = value; 26 | this.flag = flag; 27 | } 28 | 29 | public K getKey() { 30 | return key; 31 | } 32 | 33 | public T getValue() { 34 | return value; 35 | } 36 | 37 | public Flag getFlag() { 38 | return flag; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/NodeEventSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 19 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 20 | 21 | import io.reactivex.rxjava3.core.Observable; 22 | import io.reactivex.rxjava3.core.ObservableEmitter; 23 | import javafx.event.Event; 24 | import javafx.event.EventHandler; 25 | import javafx.event.EventType; 26 | import javafx.scene.Node; 27 | 28 | public class NodeEventSource { 29 | public static Observable fromNodeEvents(final Node source, final EventType eventType) { 30 | 31 | return Observable.create((ObservableEmitter emitter) -> { 32 | final EventHandler handler = emitter::onNext; 33 | 34 | source.addEventHandler(eventType, handler); 35 | 36 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeEventHandler(eventType, handler))); 37 | }).subscribeOn(JavaFxScheduler.platform()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ObservableListSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.HashMap; 19 | import java.util.function.Function; 20 | 21 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 22 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 23 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 24 | 25 | import io.reactivex.rxjava3.core.Observable; 26 | import io.reactivex.rxjava3.core.ObservableOnSubscribe; 27 | import javafx.beans.property.ListProperty; 28 | import javafx.collections.ListChangeListener; 29 | import javafx.collections.ObservableList; 30 | 31 | public final class ObservableListSource { 32 | private ObservableListSource() {} 33 | 34 | public static Observable> fromObservableList(final ObservableList source) { 35 | 36 | Observable> mutations = Observable.create((ObservableOnSubscribe>) subscriber -> { 37 | ListChangeListener listener = c -> subscriber.onNext(source); 38 | source.addListener(listener); 39 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 40 | }); 41 | 42 | 43 | if (source instanceof ListProperty) { 44 | return JavaFxObservable.valuesOf((ListProperty) source); 45 | } else { 46 | return mutations.startWithArray(source); 47 | } 48 | } 49 | 50 | public static Observable fromObservableListAdds(final ObservableList source) { 51 | 52 | return Observable.create((ObservableOnSubscribe) subscriber -> { 53 | 54 | ListChangeListener listener = c -> { 55 | while (c.next()) { 56 | if (c.wasAdded()) { 57 | c.getAddedSubList().forEach(subscriber::onNext); 58 | } 59 | } 60 | }; 61 | source.addListener(listener); 62 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 63 | 64 | }).subscribeOn(JavaFxScheduler.platform()); 65 | } 66 | public static Observable fromObservableListRemovals(final ObservableList source) { 67 | 68 | return Observable.create((ObservableOnSubscribe) subscriber -> { 69 | 70 | ListChangeListener listener = c -> { 71 | while (c.next()) { 72 | if (c.wasRemoved()) { 73 | c.getRemoved().forEach(subscriber::onNext); 74 | } 75 | } 76 | }; 77 | 78 | source.addListener(listener); 79 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 80 | 81 | }); 82 | } 83 | public static Observable fromObservableListUpdates(final ObservableList source) { 84 | 85 | return Observable.create((ObservableOnSubscribe) subscriber -> { 86 | 87 | ListChangeListener listener = c -> { 88 | while (c.next()) { 89 | if (c.wasUpdated()) { 90 | for (int i = c.getFrom(); i < c.getTo(); i++) { 91 | subscriber.onNext(c.getList().get(i)); 92 | } 93 | } 94 | } 95 | }; 96 | source.addListener(listener); 97 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 98 | 99 | }); 100 | } 101 | public static Observable> fromObservableListChanges(final ObservableList source) { 102 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 103 | 104 | ListChangeListener listener = c -> { 105 | while (c.next()) { 106 | if (c.wasAdded()) { 107 | c.getAddedSubList().forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); 108 | } 109 | if (c.wasRemoved()) { 110 | c.getRemoved().forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); 111 | } 112 | if (c.wasUpdated()) { 113 | for (int i = c.getFrom(); i < c.getTo(); i++) { 114 | subscriber.onNext(ListChange.of(c.getList().get(i),Flag.UPDATED)); 115 | } 116 | } 117 | } 118 | }; 119 | source.addListener(listener); 120 | 121 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 122 | }); 123 | } 124 | 125 | public static Observable> fromObservableListDistinctChanges(final ObservableList source) { 126 | 127 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 128 | 129 | final DupeCounter dupeCounter = new DupeCounter<>(); 130 | source.forEach(dupeCounter::add); 131 | 132 | ListChangeListener listener = c -> { 133 | 134 | while (c.next()) { 135 | if (c.wasAdded()) { 136 | c.getAddedSubList().stream().filter(v -> dupeCounter.add(v) == 1) 137 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); 138 | } 139 | if (c.wasRemoved()) { 140 | c.getRemoved().stream().filter(v -> dupeCounter.remove(v) == 0) 141 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); 142 | } 143 | } 144 | }; 145 | source.addListener(listener); 146 | 147 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 148 | }); 149 | } 150 | public static Observable> fromObservableListDistinctChanges(final ObservableList source, Function mapper) { 151 | 152 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 153 | 154 | final DupeCounter dupeCounter = new DupeCounter<>(); 155 | source.stream().map(mapper).forEach(dupeCounter::add); 156 | 157 | ListChangeListener listener = c -> { 158 | 159 | while (c.next()) { 160 | if (c.wasAdded()) { 161 | c.getAddedSubList().stream().filter(v -> dupeCounter.add(mapper.apply(v)) == 1) 162 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); 163 | } 164 | if (c.wasRemoved()) { 165 | c.getRemoved().stream().filter(v -> dupeCounter.remove(mapper.apply(v)) == 0) 166 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); 167 | } 168 | } 169 | }; 170 | source.addListener(listener); 171 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 172 | }); 173 | } 174 | public static Observable> fromObservableListDistinctMappings(final ObservableList source, Function mapper) { 175 | 176 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 177 | 178 | final DupeCounter dupeCounter = new DupeCounter<>(); 179 | source.stream().map(mapper).forEach(dupeCounter::add); 180 | 181 | ListChangeListener listener = c -> { 182 | 183 | while (c.next()) { 184 | if (c.wasAdded()) { 185 | c.getAddedSubList().stream().map(mapper) 186 | .filter(v -> dupeCounter.add(v) == 1) 187 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.ADDED))); 188 | } 189 | if (c.wasRemoved()) { 190 | c.getRemoved().stream().map(mapper) 191 | .filter(v -> dupeCounter.remove(v) == 0) 192 | .forEach(v -> subscriber.onNext(ListChange.of(v,Flag.REMOVED))); 193 | } 194 | } 195 | }; 196 | source.addListener(listener); 197 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 198 | 199 | }); 200 | } 201 | 202 | private static final class DupeCounter { 203 | private final HashMap counts = new HashMap<>(); 204 | 205 | public int add(T value) { 206 | Integer prev = counts.get(value); 207 | int newVal = 0; 208 | if (prev == null) { 209 | newVal = 1; 210 | counts.put(value, newVal); 211 | } else { 212 | newVal = prev + 1; 213 | counts.put(value, newVal); 214 | } 215 | return newVal; 216 | } 217 | public int remove(T value) { 218 | Integer prev = counts.get(value); 219 | if (prev != null && prev > 0) { 220 | int newVal = prev - 1; 221 | if (newVal == 0) { 222 | counts.remove(value); 223 | } else { 224 | counts.put(value, newVal); 225 | } 226 | return newVal; 227 | } 228 | else { 229 | throw new IllegalStateException(); 230 | } 231 | } 232 | } 233 | 234 | } 235 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ObservableMapSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.AbstractMap.SimpleEntry; 19 | import java.util.Map.Entry; 20 | 21 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 22 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 23 | 24 | import io.reactivex.rxjava3.core.Observable; 25 | import io.reactivex.rxjava3.core.ObservableOnSubscribe; 26 | import javafx.beans.property.MapProperty; 27 | import javafx.collections.MapChangeListener; 28 | import javafx.collections.ObservableMap; 29 | 30 | public final class ObservableMapSource { 31 | 32 | private ObservableMapSource() {} 33 | 34 | public static Observable> fromObservableMap(final ObservableMap source) { 35 | Observable> mutations = Observable.create((ObservableOnSubscribe>) subscriber -> { 36 | MapChangeListener listener = c -> subscriber.onNext(source); 37 | source.addListener(listener); 38 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 39 | }); 40 | 41 | 42 | if (source instanceof MapProperty) { 43 | return JavaFxObservable.valuesOf((MapProperty) source); 44 | } else { 45 | return mutations.startWithArray(source); 46 | } 47 | } 48 | 49 | public static Observable> fromObservableMapAdds(final ObservableMap source) { 50 | 51 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 52 | 53 | MapChangeListener listener = c -> { 54 | 55 | if (c.wasAdded()) { 56 | subscriber.onNext(new SimpleEntry(c.getKey(),c.getValueAdded())); 57 | } 58 | 59 | }; 60 | source.addListener(listener); 61 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 62 | 63 | }); 64 | } 65 | 66 | public static Observable> fromObservableMapRemovals(final ObservableMap source) { 67 | 68 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 69 | 70 | MapChangeListener listener = c -> { 71 | 72 | if (c.wasRemoved()) { 73 | subscriber.onNext(new SimpleEntry(c.getKey(),c.getValueRemoved())); 74 | } 75 | 76 | }; 77 | source.addListener(listener); 78 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 79 | 80 | }); 81 | } 82 | 83 | public static Observable> fromObservableMapChanges(final ObservableMap source) { 84 | 85 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 86 | 87 | MapChangeListener listener = c -> { 88 | 89 | if (c.wasRemoved()) { 90 | subscriber.onNext(new MapChange(c.getKey(),c.getValueRemoved(),Flag.REMOVED)); 91 | } 92 | if (c.wasAdded()) { 93 | subscriber.onNext(new MapChange(c.getKey(),c.getValueAdded(),Flag.ADDED)); 94 | } 95 | 96 | }; 97 | source.addListener(listener); 98 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 99 | 100 | }); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ObservableSetSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 19 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 20 | 21 | import io.reactivex.rxjava3.core.Observable; 22 | import io.reactivex.rxjava3.core.ObservableOnSubscribe; 23 | import javafx.beans.property.SetProperty; 24 | import javafx.collections.ObservableSet; 25 | import javafx.collections.SetChangeListener; 26 | 27 | public final class ObservableSetSource { 28 | private ObservableSetSource() {} 29 | 30 | public static Observable> fromObservableSet(final ObservableSet source) { 31 | 32 | Observable> mutations = Observable.create((ObservableOnSubscribe>) subscriber -> { 33 | SetChangeListener listener = c -> subscriber.onNext(source); 34 | source.addListener(listener); 35 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 36 | }); 37 | 38 | if (source instanceof SetProperty) { 39 | return JavaFxObservable.valuesOf((SetProperty) source); 40 | } else { 41 | return mutations.startWithArray(source); 42 | } 43 | } 44 | 45 | public static Observable fromObservableSetAdds(final ObservableSet source) { 46 | 47 | return Observable.create((ObservableOnSubscribe) subscriber -> { 48 | 49 | SetChangeListener listener = c -> { 50 | if (c.wasAdded()) { 51 | subscriber.onNext(c.getElementAdded()); 52 | } 53 | }; 54 | source.addListener(listener); 55 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 56 | 57 | }); 58 | } 59 | 60 | public static Observable fromObservableSetRemovals(final ObservableSet source) { 61 | 62 | return Observable.create((ObservableOnSubscribe) subscriber -> { 63 | 64 | SetChangeListener listener = c -> { 65 | if (c.wasRemoved()) { 66 | subscriber.onNext(c.getElementRemoved()); 67 | } 68 | }; 69 | source.addListener(listener); 70 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 71 | 72 | }); 73 | } 74 | 75 | public static Observable> fromObservableSetChanges(final ObservableSet source) { 76 | 77 | return Observable.create((ObservableOnSubscribe>) subscriber -> { 78 | 79 | SetChangeListener listener = c -> { 80 | if (c.wasRemoved()) { 81 | subscriber.onNext(new SetChange(c.getElementRemoved(), Flag.REMOVED)); 82 | } 83 | if (c.wasAdded()) { 84 | subscriber.onNext(new SetChange(c.getElementAdded(), Flag.ADDED)); 85 | } 86 | }; 87 | source.addListener(listener); 88 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeListener(listener))); 89 | 90 | }); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/ObservableValueSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.Optional; 19 | 20 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 21 | 22 | import io.reactivex.rxjava3.core.Observable; 23 | import io.reactivex.rxjava3.core.ObservableEmitter; 24 | import javafx.beans.InvalidationListener; 25 | import javafx.beans.value.ChangeListener; 26 | import javafx.beans.value.ObservableValue; 27 | 28 | public class ObservableValueSource { 29 | 30 | 31 | public static Observable fromObservableValue(final ObservableValue fxObservable) { 32 | return Observable.create((ObservableEmitter emitter) -> { 33 | if (fxObservable.getValue() != null) 34 | emitter.onNext(fxObservable.getValue()); 35 | 36 | final ChangeListener listener = (observableValue, prev, current) -> { 37 | emitter.onNext(current); 38 | }; 39 | 40 | fxObservable.addListener(listener); 41 | 42 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener))); 43 | }); 44 | } 45 | 46 | public static Observable fromObservableValue(final ObservableValue fxObservable, final T nullSentinel) { 47 | if (nullSentinel == null) { 48 | throw new NullPointerException("The null value sentinel must not be null."); 49 | } 50 | return Observable.create((ObservableEmitter emitter) -> { 51 | if (fxObservable.getValue() != null) { 52 | emitter.onNext(fxObservable.getValue()); 53 | } 54 | 55 | final ChangeListener listener = (observableValue, prev, current) -> { 56 | if (current != null) { 57 | emitter.onNext(current); 58 | } else { 59 | emitter.onNext(nullSentinel); 60 | } 61 | }; 62 | 63 | fxObservable.addListener(listener); 64 | 65 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener))); 66 | }); 67 | } 68 | 69 | public static Observable> fromNullableObservableValue(final ObservableValue fxObservable) { 70 | return Observable.create((ObservableEmitter> emitter) -> { 71 | emitter.onNext(Optional.ofNullable(fxObservable.getValue())); 72 | 73 | final ChangeListener listener = (observableValue, prev, current) -> emitter.onNext(Optional.ofNullable(current)); 74 | 75 | fxObservable.addListener(listener); 76 | 77 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener))); 78 | }); 79 | } 80 | 81 | public static Observable> fromObservableValueChanges(final ObservableValue fxObservable) { 82 | return Observable.create((ObservableEmitter> emitter) -> { 83 | final ChangeListener listener = (observableValue, prev, current) -> { 84 | emitter.onNext(new Change<>(prev,current)); 85 | }; 86 | 87 | fxObservable.addListener(listener); 88 | 89 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener))); 90 | }); 91 | } 92 | 93 | 94 | public static Observable fromInvalidations(javafx.beans.Observable fxObservable) { 95 | return Observable.create(emitter -> { 96 | final InvalidationListener listener = emitter::onNext; 97 | fxObservable.addListener(listener); 98 | emitter.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> fxObservable.removeListener(listener))); 99 | }); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/SceneEventSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 19 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 20 | 21 | import io.reactivex.rxjava3.core.Observable; 22 | import io.reactivex.rxjava3.core.ObservableOnSubscribe; 23 | import javafx.event.Event; 24 | import javafx.event.EventHandler; 25 | import javafx.event.EventType; 26 | import javafx.scene.Scene; 27 | 28 | public final class SceneEventSource { 29 | 30 | public static Observable fromSceneEvents(final Scene source, final EventType eventType) { 31 | 32 | return Observable.create((ObservableOnSubscribe) subscriber -> { 33 | final EventHandler handler = subscriber::onNext; 34 | 35 | source.addEventHandler(eventType, handler); 36 | 37 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeEventHandler(eventType, handler))); 38 | 39 | }).subscribeOn(JavaFxScheduler.platform()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/SetChange.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | public final class SetChange { 19 | private final T value; 20 | private final Flag flag; 21 | 22 | SetChange(T value, Flag flag) { 23 | this.value = value; 24 | this.flag = flag; 25 | } 26 | public T getValue() { 27 | return value; 28 | } 29 | public Flag getFlag() { 30 | return flag; 31 | } 32 | @Override 33 | public String toString() { 34 | return flag + " " + value; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/TimerSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import java.util.concurrent.atomic.AtomicLong; 19 | 20 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 21 | 22 | import io.reactivex.rxjava3.core.Observable; 23 | import javafx.animation.Animation; 24 | import javafx.animation.KeyFrame; 25 | import javafx.animation.Timeline; 26 | import javafx.util.Duration; 27 | 28 | public final class TimerSource { 29 | private TimerSource() { 30 | } 31 | 32 | 33 | public static Observable interval(final Duration duration) { 34 | return Observable.create(sub -> { 35 | final AtomicLong value = new AtomicLong(0); 36 | Timeline timeline = new Timeline(new KeyFrame(duration, ae -> sub.onNext(value.getAndIncrement()))); 37 | timeline.setCycleCount(Animation.INDEFINITE); 38 | timeline.play(); 39 | 40 | sub.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(timeline::stop)); 41 | }); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/sources/WindowEventSource.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 19 | import org.pdfsam.rxjavafx.subscriptions.JavaFxSubscriptions; 20 | 21 | import io.reactivex.rxjava3.core.Observable; 22 | import io.reactivex.rxjava3.core.ObservableEmitter; 23 | import javafx.event.EventHandler; 24 | import javafx.event.EventType; 25 | import javafx.stage.Window; 26 | import javafx.stage.WindowEvent; 27 | 28 | public final class WindowEventSource { 29 | 30 | private WindowEventSource() {} 31 | 32 | public static Observable fromWindowEvents(final Window source, final EventType eventType) { 33 | 34 | return Observable.create((ObservableEmitter subscriber) -> { 35 | final EventHandler handler = subscriber::onNext; 36 | 37 | source.addEventHandler(eventType, handler); 38 | 39 | subscriber.setDisposable(JavaFxSubscriptions.unsubscribeInEventDispatchThread(() -> source.removeEventHandler(eventType, handler))); 40 | 41 | }).subscribeOn(JavaFxScheduler.platform()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/subscriptions/CompositeBinding.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.subscriptions; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Arrays; 20 | import java.util.Collection; 21 | import java.util.HashSet; 22 | import java.util.List; 23 | import java.util.Set; 24 | 25 | import io.reactivex.rxjava3.exceptions.Exceptions; 26 | import javafx.beans.binding.Binding; 27 | 28 | 29 | /** 30 | * A group of of Bindings that are disposed together. 31 | *

32 | * All methods of this class must be called on JavaFX Thread 33 | */ 34 | public final class CompositeBinding { 35 | 36 | private Set bindings; 37 | private Set compBindings; 38 | private boolean disposedInd; 39 | 40 | public CompositeBinding() {} 41 | 42 | public CompositeBinding(final Binding... bindings) { 43 | this.bindings = new HashSet<>(Arrays.asList(bindings)); 44 | } 45 | 46 | public void invalidate() { 47 | if (bindings != null) { 48 | bindings.forEach(Binding::invalidate); 49 | } 50 | if (compBindings != null) { 51 | compBindings.forEach(CompositeBinding::invalidate); 52 | } 53 | } 54 | public boolean isDisposed() { 55 | return disposedInd; 56 | } 57 | 58 | /** 59 | * Adds a new {@link CompositeBinding} to this {@code CompositeBinding} if the 60 | * {@code CompositeBinding} is not yet disposed. If the {@code CompositeBinding} is 61 | * disposed, {@code add} will indicate this by explicitly disposing the new {@code CompositeBinding} as 62 | * well. 63 | * 64 | * @param b the {@link Binding} to add 65 | */ 66 | public void add(final CompositeBinding b) { 67 | if (!disposedInd) { 68 | if (compBindings == null) { 69 | compBindings = new HashSet<>(4); 70 | } 71 | compBindings.add(b); 72 | return; 73 | } 74 | b.dispose(); 75 | } 76 | 77 | /** 78 | * Adds a new {@link Binding} to this {@code CompositeBinding} if the 79 | * {@code CompositeBinding} is not yet disposedInd. If the {@code CompositeBinding} is 80 | * disposed, {@code add} will indicate this by explicitly disposing the new {@code Binding} as 81 | * well. 82 | * 83 | * @param b the {@link Binding} to add 84 | */ 85 | public void add(final Binding b) { 86 | if (!disposedInd) { 87 | if (bindings == null) { 88 | bindings = new HashSet<>(4); 89 | } 90 | bindings.add(b); 91 | return; 92 | } 93 | b.dispose(); 94 | } 95 | 96 | /** 97 | * Removes a {@link CompositeBinding} from this {@code CompositeBinding}, and disposes the 98 | * {@link CompositeBinding}. 99 | * 100 | * @param b the {@link CompositeBinding} to remove 101 | */ 102 | public void remove(final CompositeBinding b) { 103 | if (!disposedInd) { 104 | boolean unsubscribe = false; 105 | if (compBindings == null) { 106 | return; 107 | } 108 | unsubscribe = compBindings.remove(b); 109 | if (unsubscribe) { 110 | // if we removed successfully we then need to call dispose on it 111 | b.dispose(); 112 | } 113 | } 114 | } 115 | 116 | /** 117 | * Removes a {@link Binding} from this {@code CompositeBinding}, and disposes the 118 | * {@link Binding}. 119 | * 120 | * @param b the {@link Binding} to remove 121 | */ 122 | public void remove(final Binding b) { 123 | if (!disposedInd) { 124 | boolean unsubscribe = false; 125 | if (bindings == null) { 126 | return; 127 | } 128 | unsubscribe = bindings.remove(b); 129 | if (unsubscribe) { 130 | // if we removed successfully we then need to call dispose on it 131 | b.dispose(); 132 | } 133 | } 134 | } 135 | 136 | 137 | /** 138 | * Disposes any bindings that are currently part of this {@code CompositeBinding} and remove 139 | * them from the {@code CompositeBinding} so that the {@code CompositeBinding} is empty and 140 | * able to manage new bindings. 141 | */ 142 | public void clear() { 143 | if (!disposedInd) { 144 | Collection unsubscribe1 = null; 145 | Collection unsubscribe2 = null; 146 | if (bindings == null && compBindings == null) { 147 | return; 148 | } 149 | if (bindings != null) { 150 | unsubscribe1 = bindings; 151 | bindings = null; 152 | unsubscribeFromAll(unsubscribe1); 153 | } 154 | if (compBindings != null) { 155 | unsubscribe2 = compBindings; 156 | compBindings = null; 157 | unsubscribeFromAllComposite(unsubscribe2); 158 | } 159 | } 160 | } 161 | 162 | 163 | /** 164 | * Disposes itself and all inner Bindings. 165 | *

After call of this method, new {@code Binding}s added to {@link CompositeBinding} 166 | * will be disposed immediately. 167 | */ 168 | public void dispose() { 169 | if (!disposedInd) { 170 | Collection unsubscribe1 = null; 171 | Collection unsubscribe2 = null; 172 | disposedInd = true; 173 | unsubscribe1 = bindings; 174 | unsubscribe2 = compBindings; 175 | bindings = null; 176 | compBindings = null; 177 | // we will only get here once 178 | unsubscribeFromAll(unsubscribe1); 179 | unsubscribeFromAllComposite(unsubscribe2); 180 | } 181 | } 182 | 183 | private static void unsubscribeFromAllComposite(Collection bindings) { 184 | if (bindings == null) { 185 | return; 186 | } 187 | List es = null; 188 | for (CompositeBinding b : bindings) { 189 | try { 190 | b.dispose(); 191 | } catch (Throwable e) { 192 | if (es == null) { 193 | es = new ArrayList<>(); 194 | } 195 | es.add(e); 196 | } 197 | } 198 | if (es != null) 199 | es.forEach(Exceptions::throwIfFatal); 200 | } 201 | private static void unsubscribeFromAll(Collection bindings) { 202 | if (bindings == null) { 203 | return; 204 | } 205 | List es = null; 206 | for (Binding b : bindings) { 207 | try { 208 | b.dispose(); 209 | } catch (Throwable e) { 210 | if (es == null) { 211 | es = new ArrayList<>(); 212 | } 213 | es.add(e); 214 | } 215 | } 216 | if (es != null) 217 | es.forEach(Exceptions::throwIfFatal); 218 | } 219 | 220 | /** 221 | * Returns true if this composite is not disposed and contains Bindings. 222 | * 223 | * @return {@code true} if this composite is not disposed and contains Bindings. 224 | * @since 1.0.7 225 | */ 226 | public boolean hasSubscriptions() { 227 | return !disposedInd && ((bindings != null && !bindings.isEmpty()) || (compBindings != null && !compBindings.isEmpty())); 228 | } 229 | } 230 | 231 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/subscriptions/JavaFxSubscriptions.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.subscriptions; 17 | 18 | 19 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 20 | 21 | import io.reactivex.rxjava3.core.Scheduler; 22 | import io.reactivex.rxjava3.disposables.Disposable; 23 | import javafx.application.Platform; 24 | 25 | 26 | public final class JavaFxSubscriptions { 27 | 28 | private JavaFxSubscriptions() { 29 | // no instance 30 | } 31 | 32 | /** 33 | * Create a Disposable that always runs unsubscribe in the event dispatch thread. 34 | * 35 | * @param unsubscribe the runnable to be performed in the ui thread at un-subscription 36 | * @return an Disposable that always runs unsubscribe in the event dispatch thread. 37 | */ 38 | public static Disposable unsubscribeInEventDispatchThread(final Runnable unsubscribe) { 39 | return Disposable.fromRunnable(() -> { 40 | if (Platform.isFxApplicationThread()) { 41 | unsubscribe.run(); 42 | } else { 43 | final Scheduler.Worker inner = JavaFxScheduler.platform().createWorker(); 44 | inner.schedule(() -> { 45 | unsubscribe.run(); 46 | inner.dispose(); 47 | }); 48 | } 49 | }); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/transformers/FxFlowableTransformers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.transformers; 17 | 18 | import org.reactivestreams.Subscriber; 19 | import org.reactivestreams.Subscription; 20 | 21 | import io.reactivex.rxjava3.core.FlowableOperator; 22 | import io.reactivex.rxjava3.core.FlowableTransformer; 23 | import io.reactivex.rxjava3.exceptions.Exceptions; 24 | import io.reactivex.rxjava3.functions.Action; 25 | import io.reactivex.rxjava3.functions.Consumer; 26 | import io.reactivex.rxjava3.subscribers.ResourceSubscriber; 27 | import javafx.application.Platform; 28 | 29 | 30 | public class FxFlowableTransformers { 31 | 32 | private FxFlowableTransformers() {} 33 | 34 | private static void runOnFx(T t, Consumer consumer) { 35 | Platform.runLater(() -> { 36 | try { 37 | consumer.accept(t); 38 | } catch (Throwable e) { 39 | throw Exceptions.propagate(e); 40 | } 41 | } 42 | ); 43 | } 44 | 45 | private static void runOnFx(Action action) { 46 | Platform.runLater(() -> { 47 | try { 48 | action.run(); 49 | } catch (Throwable e) { 50 | throw Exceptions.propagate(e); 51 | } 52 | } 53 | ); 54 | } 55 | 56 | /** 57 | * Performs a given action for each item on the FX thread 58 | * @param onNext 59 | * @param 60 | */ 61 | public static FlowableTransformer doOnNextFx(Consumer onNext) { 62 | return obs -> obs.doOnNext(t -> runOnFx(t, onNext)); 63 | } 64 | 65 | /** 66 | * Performs a given action on a Throwable on the FX thread in the event of an onError 67 | * @param onError 68 | * @param 69 | */ 70 | public static FlowableTransformer doOnErrorFx(Consumer onError) { 71 | return obs -> obs.doOnError(e -> runOnFx(e,onError)); 72 | } 73 | 74 | /** 75 | * Performs a given Action on the FX thread when onCompleted is called 76 | * @param onCompleted 77 | * @param 78 | */ 79 | public static FlowableTransformer doOnCompleteFx(Action onCompleted) { 80 | return obs -> obs.doOnComplete(() -> runOnFx(onCompleted)); 81 | } 82 | 83 | /** 84 | * Performs a given Action on the FX thread when subscribed to 85 | * @param subscribe 86 | * @param 87 | */ 88 | public static FlowableTransformer doOnSubscribeFx(Consumer subscribe) { 89 | return obs -> obs.doOnSubscribe((d -> runOnFx(d,subscribe))); 90 | } 91 | 92 | /** 93 | * Performs the provided onTerminate action on the FX thread 94 | * @param onTerminate 95 | * @param 96 | */ 97 | public static FlowableTransformer doOnTerminateFx(Action onTerminate) { 98 | return obs -> obs.doOnTerminate(() -> runOnFx(onTerminate)); 99 | } 100 | 101 | /** 102 | * Performs the provided onTerminate action on the FX thread 103 | * @param onDipsose 104 | * @param 105 | */ 106 | public static FlowableTransformer doOnCancelFx(Action onDipsose) { 107 | return obs -> obs.doOnCancel(() -> runOnFx(onDipsose)); 108 | } 109 | 110 | /** 111 | * Performs an action on onNext with the provided emission count 112 | * @param onNext 113 | * @param 114 | */ 115 | public static FlowableTransformer doOnNextCount(Consumer onNext) { 116 | return obs -> obs.lift(new FlowableEmissionCounter<>(new CountObserver(onNext,null,null))); 117 | } 118 | 119 | /** 120 | * Performs an action on onComplete with the provided emission count 121 | * @param onComplete 122 | * @param 123 | */ 124 | public static FlowableTransformer doOnCompleteCount(Consumer onComplete) { 125 | return obs -> obs.lift(new FlowableEmissionCounter<>(new CountObserver(null,onComplete,null))); 126 | } 127 | 128 | /** 129 | * Performs an action on onError with the provided emission count 130 | * @param onError 131 | * @param 132 | */ 133 | public static FlowableTransformer doOnErrorCount(Consumer onError) { 134 | return obs -> obs.lift(new FlowableEmissionCounter<>(new CountObserver(null,null,onError))); 135 | } 136 | 137 | /** 138 | * Performs an action on FX thread on onNext with the provided emission count 139 | * @param onNext 140 | * @param 141 | */ 142 | public static FlowableTransformer doOnNextCountFx(Consumer onNext) { 143 | return obs -> obs.compose(doOnNextCount(i -> runOnFx(i,onNext))); 144 | } 145 | 146 | /** 147 | * Performs an action on FX thread on onCompleted with the provided emission count 148 | * @param onComplete 149 | * @param 150 | */ 151 | public static FlowableTransformer doOnCompleteCountFx(Consumer onComplete) { 152 | return obs -> obs.compose(doOnCompleteCount(i -> runOnFx(i,onComplete))); 153 | } 154 | 155 | /** 156 | * Performs an action on FX thread on onError with the provided emission count 157 | * @param onError 158 | * @param 159 | */ 160 | public static FlowableTransformer doOnErrorCountFx(Consumer onError) { 161 | return obs -> obs.compose(doOnErrorCount(i -> runOnFx(i,onError))); 162 | } 163 | 164 | 165 | private static class FlowableEmissionCounter implements FlowableOperator { 166 | 167 | private final CountObserver ctObserver; 168 | 169 | FlowableEmissionCounter(CountObserver ctObserver) { 170 | this.ctObserver = ctObserver; 171 | } 172 | 173 | @Override 174 | public Subscriber apply(Subscriber child) { 175 | 176 | return new ResourceSubscriber() { 177 | private int count = 0; 178 | private boolean done = false; 179 | 180 | @Override 181 | protected void onStart() { 182 | super.onStart(); 183 | request(Long.MAX_VALUE); 184 | } 185 | 186 | @Override 187 | public void onComplete() { 188 | if (done) 189 | return; 190 | 191 | try { 192 | if (ctObserver.doOnCompletedCountAction != null) 193 | ctObserver.doOnCompletedCountAction.accept(count); 194 | } catch (Throwable e) { 195 | Exceptions.throwIfFatal(e); 196 | onError(e); 197 | return; 198 | } 199 | done = true; 200 | child.onComplete(); 201 | } 202 | 203 | @Override 204 | public void onError(Throwable e) { 205 | if (done) 206 | return; 207 | try { 208 | if (ctObserver.doOnErrorCountAction != null) 209 | ctObserver.doOnErrorCountAction.accept(count); 210 | } catch(Throwable e1) { 211 | Exceptions.throwIfFatal(e1); 212 | child.onError(e1); 213 | } 214 | } 215 | 216 | @Override 217 | public void onNext(T t) { 218 | if (done) 219 | return; 220 | try { 221 | ++count; 222 | if (ctObserver.doOnNextCountAction != null) 223 | ctObserver.doOnNextCountAction.accept(count); 224 | } catch(Throwable e) { 225 | Exceptions.throwIfFatal(e); 226 | onError(e); 227 | return; 228 | } 229 | child.onNext(t); 230 | request(Long.MAX_VALUE); 231 | } 232 | }; 233 | } 234 | } 235 | 236 | private static final class CountObserver { 237 | private final Consumer doOnNextCountAction; 238 | private final Consumer doOnCompletedCountAction; 239 | private final Consumer doOnErrorCountAction; 240 | 241 | CountObserver(Consumer doOnNextCountAction, Consumer doOnCompletedCountAction, Consumer doOnErrorCountAction) { 242 | this.doOnNextCountAction = doOnNextCountAction; 243 | this.doOnCompletedCountAction = doOnCompletedCountAction; 244 | this.doOnErrorCountAction = doOnErrorCountAction; 245 | } 246 | } 247 | 248 | } 249 | -------------------------------------------------------------------------------- /src/main/java/org/pdfsam/rxjavafx/transformers/FxObservableTransformers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.pdfsam.rxjavafx.transformers; 18 | 19 | import io.reactivex.rxjava3.core.ObservableOperator; 20 | import io.reactivex.rxjava3.core.ObservableTransformer; 21 | import io.reactivex.rxjava3.core.Observer; 22 | import io.reactivex.rxjava3.disposables.Disposable; 23 | import io.reactivex.rxjava3.exceptions.Exceptions; 24 | import io.reactivex.rxjava3.functions.Action; 25 | import io.reactivex.rxjava3.functions.Consumer; 26 | import io.reactivex.rxjava3.observers.ResourceObserver; 27 | import javafx.application.Platform; 28 | 29 | 30 | public final class FxObservableTransformers { 31 | private FxObservableTransformers() {} 32 | 33 | private static void runOnFx(T t, Consumer consumer) { 34 | Platform.runLater(() -> { 35 | try { 36 | consumer.accept(t); 37 | } catch (Throwable e) { 38 | throw Exceptions.propagate(e); 39 | } 40 | } 41 | ); 42 | } 43 | private static void runOnFx(Action action) { 44 | Platform.runLater(() -> { 45 | try { 46 | action.run(); 47 | } catch (Throwable e) { 48 | throw Exceptions.propagate(e); 49 | } 50 | } 51 | ); 52 | } 53 | 54 | /** 55 | * Performs a given action for each item on the FX thread 56 | * @param onNext 57 | * @param 58 | */ 59 | public static ObservableTransformer doOnNextFx(Consumer onNext) { 60 | return obs -> obs.doOnNext(t -> runOnFx(t, onNext)); 61 | } 62 | 63 | /** 64 | * Performs a given action on a Throwable on the FX thread in the event of an onError 65 | * @param onError 66 | * @param 67 | */ 68 | public static ObservableTransformer doOnErrorFx(Consumer onError) { 69 | return obs -> obs.doOnError(e -> runOnFx(e,onError)); 70 | } 71 | 72 | /** 73 | * Performs a given Action on the FX thread when onCompleted is called 74 | * @param onCompleted 75 | * @param 76 | */ 77 | public static ObservableTransformer doOnCompleteFx(Action onCompleted) { 78 | return obs -> obs.doOnComplete(() -> runOnFx(onCompleted)); 79 | } 80 | 81 | /** 82 | * Performs a given Action on the FX thread when subscribed to 83 | * @param subscribe 84 | * @param 85 | */ 86 | public static ObservableTransformer doOnSubscribeFx(Consumer subscribe) { 87 | return obs -> obs.doOnSubscribe((d -> runOnFx(d,subscribe))); 88 | } 89 | 90 | /** 91 | * Performs the provided onTerminate action on the FX thread 92 | * @param onTerminate 93 | * @param 94 | */ 95 | public static ObservableTransformer doOnTerminateFx(Action onTerminate) { 96 | return obs -> obs.doOnTerminate(() -> runOnFx(onTerminate)); 97 | } 98 | 99 | /** 100 | * Performs the provided onTerminate action on the FX thread 101 | * @param onDipsose 102 | * @param 103 | */ 104 | public static ObservableTransformer doOnDisposeFx(Action onDipsose) { 105 | return obs -> obs.doOnDispose(() -> runOnFx(onDipsose)); 106 | } 107 | 108 | /** 109 | * Performs an action on onNext with the provided emission count 110 | * @param onNext 111 | * @param 112 | */ 113 | public static ObservableTransformer doOnNextCount(Consumer onNext) { 114 | return obs -> obs.lift(new OperatorEmissionCounter<>(new CountObserver(onNext,null,null))); 115 | } 116 | 117 | /** 118 | * Performs an action on onComplete with the provided emission count 119 | * @param onComplete 120 | * @param 121 | */ 122 | public static ObservableTransformer doOnCompleteCount(Consumer onComplete) { 123 | return obs -> obs.lift(new OperatorEmissionCounter<>(new CountObserver(null,onComplete,null))); 124 | } 125 | 126 | /** 127 | * Performs an action on onError with the provided emission count 128 | * @param onError 129 | * @param 130 | */ 131 | public static ObservableTransformer doOnErrorCount(Consumer onError) { 132 | return obs -> obs.lift(new OperatorEmissionCounter<>(new CountObserver(null,null,onError))); 133 | } 134 | 135 | /** 136 | * Performs an action on FX thread on onNext with the provided emission count 137 | * @param onNext 138 | * @param 139 | */ 140 | public static ObservableTransformer doOnNextCountFx(Consumer onNext) { 141 | return obs -> obs.compose(doOnNextCount(i -> runOnFx(i,onNext))); 142 | } 143 | 144 | /** 145 | * Performs an action on FX thread on onCompleted with the provided emission count 146 | * @param onComplete 147 | * @param 148 | */ 149 | public static ObservableTransformer doOnCompleteCountFx(Consumer onComplete) { 150 | return obs -> obs.compose(doOnCompleteCount(i -> runOnFx(i,onComplete))); 151 | } 152 | 153 | /** 154 | * Performs an action on FX thread on onError with the provided emission count 155 | * @param onError 156 | * @param 157 | */ 158 | public static ObservableTransformer doOnErrorCountFx(Consumer onError) { 159 | return obs -> obs.compose(doOnErrorCount(i -> runOnFx(i,onError))); 160 | } 161 | 162 | 163 | private static class OperatorEmissionCounter implements ObservableOperator { 164 | 165 | private final CountObserver ctObserver; 166 | 167 | OperatorEmissionCounter(CountObserver ctObserver) { 168 | this.ctObserver = ctObserver; 169 | } 170 | 171 | @Override 172 | public Observer apply(Observer child) { 173 | 174 | return new ResourceObserver() { 175 | private int count = 0; 176 | private boolean done = false; 177 | 178 | @Override 179 | public void onComplete() { 180 | if (done) 181 | return; 182 | 183 | try { 184 | if (ctObserver.doOnCompletedCountAction != null) 185 | ctObserver.doOnCompletedCountAction.accept(count); 186 | } catch (Throwable e) { 187 | Exceptions.throwIfFatal(e); 188 | onError(e); 189 | return; 190 | } 191 | done = true; 192 | child.onComplete(); 193 | } 194 | 195 | @Override 196 | public void onError(Throwable e) { 197 | if (done) 198 | return; 199 | try { 200 | if (ctObserver.doOnErrorCountAction != null) 201 | ctObserver.doOnErrorCountAction.accept(count); 202 | } catch(Throwable e1) { 203 | Exceptions.throwIfFatal(e1); 204 | child.onError(e1); 205 | } 206 | } 207 | 208 | @Override 209 | public void onNext(T t) { 210 | if (done) 211 | return; 212 | try { 213 | ++count; 214 | if (ctObserver.doOnNextCountAction != null) 215 | ctObserver.doOnNextCountAction.accept(count); 216 | } catch(Throwable e) { 217 | Exceptions.throwIfFatal(e); 218 | onError(e); 219 | return; 220 | } 221 | child.onNext(t); 222 | } 223 | }; 224 | } 225 | } 226 | private static final class CountObserver { 227 | private final Consumer doOnNextCountAction; 228 | private final Consumer doOnCompletedCountAction; 229 | private final Consumer doOnErrorCountAction; 230 | 231 | CountObserver(Consumer doOnNextCountAction, Consumer doOnCompletedCountAction, Consumer doOnErrorCountAction) { 232 | this.doOnNextCountAction = doOnNextCountAction; 233 | this.doOnCompletedCountAction = doOnCompletedCountAction; 234 | this.doOnErrorCountAction = doOnErrorCountAction; 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/test/java/org/pdfsam/rxjavafx/RxJavaFXTest.java: -------------------------------------------------------------------------------- 1 | package org.pdfsam.rxjavafx; 2 | 3 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 4 | import org.pdfsam.rxjavafx.observers.JavaFxObserver; 5 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 6 | 7 | import io.reactivex.rxjava3.core.Observable; 8 | import io.reactivex.rxjava3.disposables.Disposable; 9 | import io.reactivex.rxjava3.schedulers.Schedulers; 10 | import javafx.application.Application; 11 | import javafx.beans.binding.Binding; 12 | import javafx.event.ActionEvent; 13 | import javafx.scene.Scene; 14 | import javafx.scene.control.Button; 15 | import javafx.scene.control.Label; 16 | import javafx.scene.control.Spinner; 17 | import javafx.scene.control.SpinnerValueFactory; 18 | import javafx.scene.control.TextField; 19 | import javafx.scene.layout.GridPane; 20 | import javafx.stage.Stage; 21 | 22 | public class RxJavaFXTest extends Application { 23 | 24 | private final Button incrementBttn; 25 | private final Label incrementLabel; 26 | private final Binding binding1; 27 | 28 | private final TextField textInput; 29 | private final Label flippedTextLabel; 30 | private final Binding binding2; 31 | 32 | private final Spinner spinner; 33 | private final Label spinnerChangesLabel; 34 | private final Disposable disposable; 35 | 36 | public RxJavaFXTest() { 37 | 38 | //initialize increment 39 | //demoTurns button events into Binding 40 | incrementBttn = new Button("Increment"); 41 | incrementLabel = new Label(""); 42 | 43 | Observable bttnEvents = 44 | JavaFxObservable.actionEventsOf(incrementBttn); 45 | 46 | binding1 = bttnEvents.map(e -> 1).scan(0,(x, y) -> x + y) 47 | .map(Object::toString) 48 | .to(JavaFxObserver::toBinding); 49 | 50 | incrementLabel.textProperty().bind(binding1); 51 | 52 | //initialize text flipper 53 | //Schedules on computation Scheduler for text flip calculation 54 | //Then resumes on JavaFxScheduler thread to update Binding 55 | textInput = new TextField(); 56 | flippedTextLabel = new Label(); 57 | 58 | Observable textInputs = 59 | JavaFxObservable.valuesOf(textInput.textProperty()); 60 | 61 | binding2 = textInputs.observeOn(Schedulers.computation()) 62 | .map(s -> new StringBuilder(s).reverse().toString()) 63 | .observeOn(JavaFxScheduler.platform()) 64 | .to(JavaFxObserver::toBinding); 65 | 66 | flippedTextLabel.textProperty().bind(binding2); 67 | 68 | //initialize Spinner value changes 69 | //Emits Change items containing old and new value 70 | //Uses RxJava Subscription instead of Binding just to show that option 71 | SpinnerValueFactory svf = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100); 72 | spinner = new Spinner<>(); 73 | spinner.setValueFactory(svf); 74 | spinner.setEditable(true); 75 | 76 | spinnerChangesLabel = new Label(); 77 | disposable = JavaFxObservable.changesOf(spinner.valueProperty()) 78 | .map(change -> "OLD: " + change.getOldVal() + " NEW: " + change.getNewVal()) 79 | .subscribe(spinnerChangesLabel::setText); 80 | 81 | } 82 | 83 | @Override 84 | public void start(Stage primaryStage) throws Exception { 85 | 86 | GridPane gridPane = new GridPane(); 87 | 88 | gridPane.setHgap(10); 89 | gridPane.setVgap(10); 90 | 91 | gridPane.add(incrementBttn,0,0); 92 | gridPane.add(incrementLabel,1,0); 93 | 94 | gridPane.add(textInput,0,1); 95 | gridPane.add(flippedTextLabel, 1,1); 96 | 97 | gridPane.add(spinner,0,2); 98 | gridPane.add(spinnerChangesLabel,1,2); 99 | 100 | Scene scene = new Scene(gridPane); 101 | 102 | 103 | primaryStage.setWidth(275); 104 | primaryStage.setScene(scene); 105 | primaryStage.show(); 106 | } 107 | 108 | @Override 109 | public void stop() throws Exception { 110 | super.stop(); 111 | 112 | binding1.dispose(); 113 | binding2.dispose(); 114 | disposable.dispose(); 115 | } 116 | } -------------------------------------------------------------------------------- /src/test/java/org/pdfsam/rxjavafx/operators/OperatorsTest.java: -------------------------------------------------------------------------------- 1 | package org.pdfsam.rxjavafx.operators; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | 8 | import org.junit.jupiter.api.Test; 9 | import org.pdfsam.rxjavafx.transformers.FxFlowableTransformers; 10 | import org.pdfsam.rxjavafx.transformers.FxObservableTransformers; 11 | 12 | import io.reactivex.rxjava3.core.Flowable; 13 | import io.reactivex.rxjava3.core.Observable; 14 | 15 | import static org.junit.jupiter.api.Assertions.assertTrue; 16 | 17 | public final class OperatorsTest { 18 | 19 | @Test 20 | public void testDoOnNextCountObservable() { 21 | 22 | final List onNextCounts = new ArrayList<>(); 23 | 24 | Observable.just("Alpha", "Beta", "Gamma") 25 | .compose(FxObservableTransformers.doOnNextCount(onNextCounts::add)) 26 | .subscribe(); 27 | 28 | assertTrue(onNextCounts.containsAll(Arrays.asList(1, 2, 3))); 29 | } 30 | 31 | @Test 32 | public void testDoOnCompleteCountObservable() { 33 | AtomicInteger onCompleteCount = new AtomicInteger(); 34 | 35 | 36 | Observable.just("Alpha", "Beta", "Gamma") 37 | .compose(FxObservableTransformers.doOnCompleteCount(onCompleteCount::set)) 38 | .subscribe(); 39 | 40 | assertTrue(onCompleteCount.get() == 3); 41 | } 42 | 43 | @Test 44 | public void testDoOnErrorCountObservable() { 45 | AtomicInteger onErrorCount = new AtomicInteger(); 46 | 47 | 48 | Observable.just(5, 10, 15, 0, 20) 49 | .map(i -> 5 / i) 50 | .compose(FxObservableTransformers.doOnErrorCount(onErrorCount::set)) 51 | .subscribe(); 52 | 53 | assertTrue(onErrorCount.get() == 3); 54 | } 55 | 56 | 57 | @Test 58 | public void testDoOnNextCountFlowable() { 59 | 60 | final List onNextCounts = new ArrayList<>(); 61 | 62 | 63 | Flowable.just("Alpha", "Beta", "Gamma") 64 | .compose(FxFlowableTransformers.doOnNextCount(onNextCounts::add)) 65 | .subscribe(); 66 | 67 | assertTrue(onNextCounts.containsAll(Arrays.asList(1, 2, 3))); 68 | } 69 | 70 | @Test 71 | public void testDoOnCompleteCountFlowable() { 72 | AtomicInteger onCompleteCount = new AtomicInteger(); 73 | 74 | 75 | Flowable.just("Alpha", "Beta", "Gamma") 76 | .compose(FxFlowableTransformers.doOnCompleteCount(onCompleteCount::set)) 77 | .subscribe(); 78 | 79 | assertTrue(onCompleteCount.get() == 3); 80 | } 81 | 82 | @Test 83 | public void testDoOnErrorCountFlowable() { 84 | AtomicInteger onErrorCount = new AtomicInteger(); 85 | 86 | 87 | Flowable.just(5, 10, 15, 0, 20) 88 | .map(i -> 5 / i) 89 | .compose(FxFlowableTransformers.doOnErrorCount(onErrorCount::set)) 90 | .subscribe(); 91 | 92 | assertTrue(onErrorCount.get() == 3); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/org/pdfsam/rxjavafx/schedulers/JavaFxSchedulerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.schedulers; 17 | 18 | import static org.junit.jupiter.api.Assertions.assertEquals; 19 | import static org.junit.jupiter.api.Assertions.assertTrue; 20 | import static org.junit.jupiter.api.Assertions.fail; 21 | import static org.mockito.Mockito.inOrder; 22 | import static org.mockito.Mockito.mock; 23 | import static org.mockito.Mockito.times; 24 | import static org.mockito.Mockito.verify; 25 | 26 | import java.util.concurrent.CountDownLatch; 27 | import java.util.concurrent.ExecutionException; 28 | import java.util.concurrent.TimeUnit; 29 | import java.util.concurrent.atomic.AtomicBoolean; 30 | import java.util.concurrent.locks.Condition; 31 | import java.util.concurrent.locks.Lock; 32 | import java.util.concurrent.locks.ReentrantLock; 33 | 34 | import org.junit.jupiter.api.BeforeAll; 35 | import org.junit.jupiter.api.Test; 36 | import org.mockito.InOrder; 37 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 38 | 39 | import io.reactivex.rxjava3.core.Scheduler; 40 | import javafx.application.Application; 41 | import javafx.application.Platform; 42 | import javafx.stage.Stage; 43 | 44 | /** 45 | * Executes work on the JavaFx UI thread. 46 | * This scheduler should only be used with actions that execute quickly. 47 | */ 48 | public final class JavaFxSchedulerTest { 49 | 50 | private static void waitForEmptyEventQueue() throws Exception { 51 | FXUtilities.runAndWait(() -> { 52 | // nothing to do, we're just waiting here for the event queue to be emptied 53 | }); 54 | } 55 | 56 | public static class AsNonApp extends Application { 57 | @Override 58 | public void start(Stage primaryStage) throws Exception { 59 | // noop 60 | } 61 | } 62 | 63 | @BeforeAll 64 | public static void initJFX() { 65 | try { 66 | javafx.application.Platform.startup(() ->{}); 67 | }catch(final IllegalStateException ignore) { 68 | } 69 | } 70 | 71 | @Test 72 | public void testPeriodicScheduling() throws Exception { 73 | final JavaFxScheduler scheduler = new JavaFxScheduler(); 74 | final Scheduler.Worker inner = scheduler.createWorker(); 75 | 76 | final CountDownLatch latch = new CountDownLatch(4); 77 | 78 | final Runnable innerAction = mock(Runnable.class); 79 | 80 | final Runnable action = () -> { 81 | try { 82 | innerAction.run(); 83 | assertTrue(Platform.isFxApplicationThread()); 84 | } finally { 85 | latch.countDown(); 86 | } 87 | }; 88 | 89 | inner.schedulePeriodically(action, 100, 400, TimeUnit.MILLISECONDS); 90 | 91 | if (!latch.await(5, TimeUnit.SECONDS)) { 92 | fail("timed out waiting for tasks to execute"); 93 | } 94 | 95 | inner.dispose(); 96 | waitForEmptyEventQueue(); 97 | verify(innerAction, times(4)).run(); 98 | } 99 | 100 | @Test 101 | public void testNestedActions() throws Exception { 102 | final JavaFxScheduler scheduler = new JavaFxScheduler(); 103 | final Scheduler.Worker inner = scheduler.createWorker(); 104 | 105 | final CountDownLatch startAsync = new CountDownLatch(1); 106 | final CountDownLatch asyncStarted = new CountDownLatch(1); 107 | final AtomicBoolean directInvocation = new AtomicBoolean(false); 108 | 109 | TestAction a1n1 = TestAction.of("A1N1", () -> assertTrue(directInvocation.get())); 110 | TestAction a1n2 = TestAction.of("A1N2", () -> assertTrue(directInvocation.get())); 111 | TestAction a1n = TestAction.of("A1N", () -> { 112 | assertTrue(directInvocation.get()); 113 | inner.schedule(a1n1); 114 | inner.schedule(a1n2); 115 | }); 116 | TestAction a2n1 = TestAction.of("A2N1", () -> assertTrue(directInvocation.get())); 117 | TestAction a2n2 = TestAction.of("A2N2", () -> assertTrue(directInvocation.get())); 118 | TestAction a2n = TestAction.of("A2N", () -> { 119 | assertTrue(directInvocation.get()); 120 | inner.schedule(a2n1); 121 | inner.schedule(a2n2); 122 | }); 123 | TestAction a = TestAction.of("A", () -> { 124 | directInvocation.set(true); 125 | Platform.runLater(() -> directInvocation.set(false)); 126 | 127 | inner.schedule(a1n); 128 | startAsync.countDown(); 129 | try { 130 | asyncStarted.await(1, TimeUnit.SECONDS); 131 | } catch (Exception e) { 132 | fail(); 133 | } 134 | inner.schedule(a2n); 135 | }); 136 | TestAction b = TestAction.of("B", () -> {}); 137 | TestAction async = TestAction.of("ASYNC", () -> {}); 138 | 139 | inner.schedule(a); 140 | inner.schedule(b); 141 | 142 | startAsync.await(); 143 | inner.schedule(async); 144 | asyncStarted.countDown(); 145 | 146 | waitForEmptyEventQueue(); 147 | 148 | TestAction.verifyOrder(a, b, a1n, async, a2n, a1n1, a1n2, a2n1, a2n2); 149 | } 150 | 151 | static class TestAction implements Runnable { 152 | private final Runnable userRunnable; 153 | private final Runnable start; 154 | private final Runnable end; 155 | 156 | public static TestAction of(String name, Runnable runnable) { 157 | return new TestAction(name, runnable); 158 | } 159 | 160 | private TestAction(String name, Runnable userRunnable) { 161 | this.userRunnable = userRunnable; 162 | this.start = mock(Runnable.class, name + "-Start"); 163 | this.end = mock(Runnable.class, name + "-End"); 164 | } 165 | 166 | @Override 167 | public void run() { 168 | assertTrue(Platform.isFxApplicationThread()); 169 | start.run(); 170 | userRunnable.run(); 171 | end.run(); 172 | } 173 | 174 | public static void verifyOrder(TestAction... actions) { 175 | Runnable[] runnables = new Runnable[actions.length * 2]; 176 | for (int i = 0; i < actions.length; i++) { 177 | TestAction action = actions[i]; 178 | runnables[2 * i] = action.start; 179 | runnables[2 * i + 1] = action.end; 180 | } 181 | InOrder inOrder = inOrder((Object[]) runnables); 182 | for (Runnable runnable : runnables) { 183 | inOrder.verify(runnable).run(); 184 | } 185 | } 186 | } 187 | 188 | 189 | @Test 190 | public void bombardScheduler() { 191 | Scheduler.Worker w = JavaFxScheduler.platform().createWorker(); 192 | 193 | CountDownLatch cdl = new CountDownLatch(2); 194 | int[] counter = { 0, 0 }; 195 | 196 | new Thread(() -> { 197 | for (int i = 0; i < 1_000_000; i++) { 198 | w.schedule(() -> counter[0]++); 199 | } 200 | w.schedule(cdl::countDown); 201 | }).start(); 202 | 203 | for (int i = 0; i < 1_000_000; i++) { 204 | w.schedule(() -> counter[1]++); 205 | } 206 | w.schedule(cdl::countDown); 207 | 208 | try { 209 | cdl.await(); 210 | } catch (InterruptedException e) { 211 | e.printStackTrace(); 212 | } 213 | 214 | assertEquals(1_000_000, counter[0]); 215 | assertEquals(1_000_000, counter[1]); 216 | 217 | w.dispose(); 218 | } 219 | 220 | /* 221 | * based on http://www.guigarage.com/2013/01/invokeandwait-for-javafx/ 222 | * by hendrikebbers 223 | */ 224 | static public class FXUtilities { 225 | 226 | /** 227 | * Simple helper class. 228 | * 229 | * @author hendrikebbers 230 | */ 231 | private static class ThrowableWrapper { 232 | Throwable t; 233 | } 234 | 235 | /** 236 | * Invokes a Runnable in JFX Thread and waits while it's finished. Like 237 | * SwingUtilities.invokeAndWait does for EDT. 238 | * 239 | * @param run The Runnable that has to be called on JFX thread. 240 | * @throws InterruptedException f the execution is interrupted. 241 | * @throws ExecutionException If a exception is occurred in the run method of the Runnable 242 | */ 243 | public static void runAndWait( final Runnable run) throws InterruptedException, ExecutionException { 244 | if (Platform.isFxApplicationThread()) { 245 | try { 246 | run.run(); 247 | } catch (Exception e) { 248 | throw new ExecutionException(e); 249 | } 250 | } else { 251 | final Lock lock = new ReentrantLock(); 252 | final Condition condition = lock.newCondition(); 253 | final ThrowableWrapper throwableWrapper = new ThrowableWrapper(); 254 | lock.lock(); 255 | try { 256 | Platform.runLater(() -> { 257 | lock.lock(); 258 | try { 259 | run.run(); 260 | } catch (Throwable e) { 261 | throwableWrapper.t = e; 262 | } finally { 263 | try { 264 | condition.signal(); 265 | } finally { 266 | lock.unlock(); 267 | } 268 | } 269 | }); 270 | condition.await(); 271 | if (throwableWrapper.t != null) { 272 | throw new ExecutionException(throwableWrapper.t); 273 | } 274 | } finally { 275 | lock.unlock(); 276 | } 277 | } 278 | } 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /src/test/java/org/pdfsam/rxjavafx/sources/JavaFxObservableTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.sources; 17 | 18 | import io.reactivex.rxjava3.core.Observable; 19 | import io.reactivex.rxjava3.observers.TestObserver; 20 | import io.reactivex.rxjava3.schedulers.Schedulers; 21 | import javafx.application.Platform; 22 | import javafx.beans.property.ListProperty; 23 | import javafx.beans.property.Property; 24 | import javafx.beans.property.ReadOnlyStringWrapper; 25 | import javafx.beans.property.SimpleListProperty; 26 | import javafx.beans.property.SimpleObjectProperty; 27 | import javafx.beans.property.SimpleStringProperty; 28 | import javafx.collections.FXCollections; 29 | import javafx.collections.ObservableList; 30 | import javafx.util.Duration; 31 | import org.junit.jupiter.api.BeforeAll; 32 | import org.junit.jupiter.api.Test; 33 | import org.pdfsam.rxjavafx.observables.JavaFxObservable; 34 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 35 | 36 | import java.util.Arrays; 37 | import java.util.List; 38 | import java.util.concurrent.CountDownLatch; 39 | 40 | import static org.junit.jupiter.api.Assertions.assertTrue; 41 | 42 | public final class JavaFxObservableTest { 43 | 44 | @BeforeAll 45 | public static void initJFX() { 46 | try { 47 | javafx.application.Platform.startup(() -> { 48 | }); 49 | } catch (final IllegalStateException ignore) { 50 | } 51 | } 52 | 53 | @Test 54 | public void testIntervalSource() { 55 | 56 | final CountDownLatch latch = new CountDownLatch(5); 57 | 58 | JavaFxObservable.interval(Duration.millis(1000)).take(5).subscribe(v -> latch.countDown()); 59 | 60 | try { 61 | latch.await(); 62 | } catch (Exception e) { 63 | throw new RuntimeException(e); 64 | } 65 | } 66 | 67 | @Test 68 | public void testListEmitOnChanged() { 69 | 70 | ObservableList sourceList = FXCollections.observableArrayList("Alpha", "Beta", "Gamma"); 71 | 72 | TestObserver> testObserver = new TestObserver<>(); 73 | 74 | JavaFxObservable.emitOnChanged(sourceList).subscribe(testObserver); 75 | 76 | testObserver.assertValueCount(1); 77 | 78 | sourceList.add("Delta"); 79 | 80 | testObserver.assertValueCount(2); 81 | } 82 | 83 | @Test 84 | public void testListPropertyEmitOnChanged() { 85 | 86 | ListProperty sourceList = new SimpleListProperty<>( 87 | FXCollections.observableArrayList("Alpha", "Beta", "Gamma")); 88 | 89 | TestObserver> testObserver = new TestObserver<>(); 90 | 91 | JavaFxObservable.emitOnChanged(sourceList).subscribe(testObserver); 92 | 93 | testObserver.assertValueCount(1); 94 | 95 | sourceList.add("Delta"); 96 | 97 | testObserver.assertValueCount(2); 98 | 99 | sourceList.setValue(FXCollections.observableArrayList("Zeta", "Eta", "Iota")); 100 | 101 | testObserver.assertValueCount(3); 102 | } 103 | 104 | @Test 105 | public void testRxObservableChanges() { 106 | Property sourceProperty = new SimpleStringProperty(); 107 | Observable> emissions = JavaFxObservable.changesOf(sourceProperty).take(4); 108 | 109 | TestObserver> testObserver = new TestObserver<>(); 110 | 111 | emissions.subscribe(testObserver); 112 | 113 | sourceProperty.setValue("Alpha"); 114 | sourceProperty.setValue("Beta"); 115 | sourceProperty.setValue(null); 116 | sourceProperty.setValue("Gamma"); 117 | 118 | testObserver.assertValues(new Change<>(null, "Alpha"), new Change<>("Alpha", "Beta"), 119 | new Change<>("Beta", null), new Change<>(null, "Gamma")); 120 | } 121 | 122 | @Test 123 | public void testRxObservableListAdds() { 124 | 125 | ObservableList sourceList = FXCollections.observableArrayList(); 126 | Observable emissions = JavaFxObservable.additionsOf(sourceList); 127 | 128 | CountDownLatch gate = new CountDownLatch(1); 129 | 130 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(3).toList().toObservable() 131 | .subscribe(l -> assertTrue(l.equals(Arrays.asList("Alpha", "Beta", "Gamma"))), 132 | Throwable::printStackTrace, gate::countDown); 133 | ; 134 | 135 | Platform.runLater(() -> { 136 | sourceList.add("Alpha"); 137 | sourceList.add("Beta"); 138 | sourceList.remove("Alpha"); 139 | sourceList.add("Gamma"); 140 | }); 141 | 142 | try { 143 | gate.await(); 144 | } catch (InterruptedException e) { 145 | throw new RuntimeException(e); 146 | } 147 | 148 | } 149 | 150 | @Test 151 | public void testRxObservableListRemoves() { 152 | 153 | ObservableList sourceList = FXCollections.observableArrayList(); 154 | Observable emissions = JavaFxObservable.removalsOf(sourceList); 155 | 156 | CountDownLatch gate = new CountDownLatch(1); 157 | 158 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(2).toSortedList().toObservable() 159 | .subscribe(l -> assertTrue(l.equals(Arrays.asList("Alpha", "Gamma"))), Throwable::printStackTrace, 160 | gate::countDown); 161 | 162 | Platform.runLater(() -> { 163 | sourceList.add("Alpha"); 164 | sourceList.add("Beta"); 165 | sourceList.remove("Alpha"); 166 | sourceList.add("Gamma"); 167 | sourceList.remove("Gamma"); 168 | }); 169 | 170 | try { 171 | gate.await(); 172 | } catch (InterruptedException e) { 173 | e.printStackTrace(); 174 | } 175 | } 176 | 177 | @Test 178 | public void testRxObservableListChanges() { 179 | //new JFXPanel()(); 180 | 181 | ObservableList sourceList = FXCollections.observableArrayList(); 182 | Observable> emissions = JavaFxObservable.changesOf(sourceList); 183 | 184 | CountDownLatch gate = new CountDownLatch(1); 185 | 186 | class FlagAndCount { 187 | final Flag flag; 188 | final long count; 189 | 190 | FlagAndCount(Flag flag, long count) { 191 | this.flag = flag; 192 | this.count = count; 193 | } 194 | 195 | } 196 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(5).groupBy(ListChange::getFlag) 197 | .flatMapSingle(grp -> grp.count().map(ct -> new FlagAndCount(grp.getKey(), ct))).subscribe(l -> { 198 | if (l.flag.equals(Flag.ADDED)) { 199 | assertTrue(l.count == 3); 200 | } 201 | if (l.flag.equals(Flag.REMOVED)) { 202 | assertTrue(l.count == 2); 203 | } 204 | }, Throwable::printStackTrace, gate::countDown); 205 | 206 | Platform.runLater(() -> { 207 | sourceList.add("Alpha"); 208 | sourceList.add("Beta"); 209 | sourceList.remove("Alpha"); 210 | sourceList.add("Gamma"); 211 | sourceList.remove("Gamma"); 212 | }); 213 | 214 | try { 215 | gate.await(); 216 | } catch (InterruptedException e) { 217 | e.printStackTrace(); 218 | } 219 | } 220 | 221 | @Test 222 | public void testRxObservableListDistinctChangeMappings() { 223 | 224 | ObservableList sourceList = FXCollections.observableArrayList(); 225 | Observable> emissions = JavaFxObservable.distinctMappingsOf(sourceList, String::length); 226 | 227 | CountDownLatch gate = new CountDownLatch(1); 228 | 229 | class FlagAndCount { 230 | final Flag flag; 231 | final long count; 232 | 233 | FlagAndCount(Flag flag, long count) { 234 | this.flag = flag; 235 | this.count = count; 236 | } 237 | 238 | } 239 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(3).groupBy(ListChange::getFlag) 240 | .flatMapSingle(grp -> grp.count().map(ct -> new FlagAndCount(grp.getKey(), ct))).subscribe(l -> { 241 | if (l.flag.equals(Flag.ADDED)) { 242 | assertTrue(l.count == 2); 243 | } 244 | if (l.flag.equals(Flag.REMOVED)) { 245 | assertTrue(l.count == 1); 246 | } 247 | }, Throwable::printStackTrace, gate::countDown); 248 | 249 | Platform.runLater(() -> { 250 | sourceList.add("Alpha"); 251 | sourceList.add("Beta"); 252 | sourceList.add("Alpha"); 253 | sourceList.remove("Alpha"); 254 | sourceList.add("Gamma"); 255 | sourceList.remove("Gamma"); 256 | sourceList.remove("Alpha"); 257 | }); 258 | 259 | try { 260 | gate.await(); 261 | } catch (InterruptedException e) { 262 | e.printStackTrace(); 263 | } 264 | } 265 | 266 | @Test 267 | public void testRxObservableListDistinctChanges() { 268 | //new JFXPanel()(); 269 | 270 | ObservableList sourceList = FXCollections.observableArrayList(); 271 | Observable> emissions = JavaFxObservable.distinctChangesOf(sourceList); 272 | 273 | CountDownLatch gate = new CountDownLatch(1); 274 | 275 | class FlagAndCount { 276 | final Flag flag; 277 | final long count; 278 | 279 | FlagAndCount(Flag flag, long count) { 280 | this.flag = flag; 281 | this.count = count; 282 | } 283 | 284 | } 285 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(5).groupBy(ListChange::getFlag) 286 | .flatMapSingle(grp -> grp.count().map(ct -> new FlagAndCount(grp.getKey(), ct))).subscribe(l -> { 287 | if (l.flag.equals(Flag.ADDED)) { 288 | assertTrue(l.count == 3); 289 | } 290 | if (l.flag.equals(Flag.REMOVED)) { 291 | assertTrue(l.count == 2); 292 | } 293 | }, Throwable::printStackTrace, gate::countDown); 294 | 295 | Platform.runLater(() -> { 296 | sourceList.add("Alpha"); 297 | sourceList.add("Beta"); 298 | sourceList.add("Alpha"); 299 | sourceList.remove("Alpha"); 300 | sourceList.add("Gamma"); 301 | sourceList.remove("Gamma"); 302 | sourceList.remove("Alpha"); 303 | }); 304 | 305 | try { 306 | gate.await(); 307 | } catch (InterruptedException e) { 308 | e.printStackTrace(); 309 | } 310 | } 311 | 312 | @Test 313 | public void testRxObservableListUpdates() { 314 | 315 | class Person { 316 | Property name; 317 | Property age = new SimpleObjectProperty<>(); 318 | 319 | Person(String name, Integer age) { 320 | this.name = new ReadOnlyStringWrapper(name); 321 | this.age.setValue(age); 322 | } 323 | 324 | @Override 325 | public String toString() { 326 | return name.getValue(); 327 | } 328 | } 329 | 330 | Person person1 = new Person("Tom Salma", 23); 331 | Person person2 = new Person("Jacob Mores", 31); 332 | Person person3 = new Person("Sally Reyes", 32); 333 | 334 | ObservableList sourceList = FXCollections.observableArrayList( 335 | user -> new javafx.beans.Observable[] { user.age }); 336 | Observable emissions = JavaFxObservable.updatesOf(sourceList); 337 | 338 | CountDownLatch gate = new CountDownLatch(1); 339 | 340 | emissions.observeOn(Schedulers.io()).observeOn(JavaFxScheduler.platform()).take(2).count().toObservable() 341 | .subscribe(ct -> assertTrue(ct == 2), Throwable::printStackTrace, gate::countDown); 342 | 343 | Platform.runLater(() -> { 344 | sourceList.addAll(person1, person2, person3); 345 | person1.age.setValue(24); 346 | person2.age.setValue(32); 347 | }); 348 | 349 | try { 350 | gate.await(); 351 | } catch (InterruptedException e) { 352 | e.printStackTrace(); 353 | } 354 | } 355 | 356 | } 357 | -------------------------------------------------------------------------------- /src/test/java/org/pdfsam/rxjavafx/subscriptions/BindingTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Netflix, Inc. 3 | *

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

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

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package org.pdfsam.rxjavafx.subscriptions; 17 | 18 | import io.reactivex.rxjava3.core.Flowable; 19 | import io.reactivex.rxjava3.core.Observable; 20 | import io.reactivex.rxjava3.processors.PublishProcessor; 21 | import io.reactivex.rxjava3.subjects.PublishSubject; 22 | import javafx.application.Platform; 23 | import javafx.beans.binding.Binding; 24 | import org.junit.jupiter.api.BeforeAll; 25 | import org.junit.jupiter.api.Test; 26 | import org.pdfsam.rxjavafx.observers.JavaFxObserver; 27 | import org.pdfsam.rxjavafx.observers.JavaFxSubscriber; 28 | import org.pdfsam.rxjavafx.schedulers.JavaFxScheduler; 29 | 30 | import java.util.Optional; 31 | import java.util.concurrent.CountDownLatch; 32 | import java.util.concurrent.TimeUnit; 33 | import java.util.concurrent.atomic.AtomicInteger; 34 | 35 | import static org.junit.jupiter.api.Assertions.assertEquals; 36 | import static org.junit.jupiter.api.Assertions.assertNull; 37 | import static org.junit.jupiter.api.Assertions.assertTrue; 38 | 39 | public final class BindingTest { 40 | 41 | @BeforeAll 42 | public static void initJFX() { 43 | try { 44 | javafx.application.Platform.startup(() -> { 45 | }); 46 | } catch (final IllegalStateException ignore) { 47 | } 48 | } 49 | 50 | @Test 51 | public void testCompositeBinding() { 52 | CompositeBinding bindings = new CompositeBinding(); 53 | 54 | Observable source = Observable.interval(1, TimeUnit.SECONDS); 55 | CountDownLatch unsubscribeWait = new CountDownLatch(2); 56 | 57 | Binding binding1 = JavaFxObserver.toBinding( 58 | source.doOnDispose(unsubscribeWait::countDown).observeOn(JavaFxScheduler.platform())); 59 | bindings.add(binding1); 60 | 61 | Binding binding2 = JavaFxObserver.toBinding( 62 | source.doOnDispose(unsubscribeWait::countDown).reduce(0L, (x, y) -> x + y) 63 | .observeOn(JavaFxScheduler.platform()).toObservable()); 64 | bindings.add(binding2); 65 | 66 | sleep(3000); 67 | assertTrue(bindings.hasSubscriptions()); 68 | 69 | bindings.dispose(); 70 | 71 | try { 72 | unsubscribeWait.await(10, TimeUnit.SECONDS); 73 | } catch (InterruptedException e) { 74 | e.printStackTrace(); 75 | } 76 | } 77 | 78 | @Test 79 | public void testObserverBinding() { 80 | final CountDownLatch latch = new CountDownLatch(1); 81 | Platform.runLater(() -> { 82 | 83 | final AtomicInteger emissionCount = new AtomicInteger(0); 84 | 85 | Observable items = Observable.just("Alpha", "Beta", "Gamma", "Delta") 86 | .doOnNext(s -> emissionCount.incrementAndGet()); 87 | 88 | Binding binding = JavaFxObserver.toBinding(items); 89 | 90 | assertEquals(4, emissionCount.get()); 91 | assertEquals("Delta", binding.getValue()); 92 | latch.countDown(); 93 | }); 94 | 95 | try { 96 | latch.await(); 97 | } catch (InterruptedException e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | 102 | @Test 103 | public void testObserverNullBinding() { 104 | final CountDownLatch latch = new CountDownLatch(1); 105 | Platform.runLater(() -> { 106 | 107 | String nil = "null"; 108 | PublishSubject items = PublishSubject.create(); 109 | Binding binding = JavaFxObserver.toNullBinding(items, nil); 110 | items.onNext(nil); 111 | 112 | assertNull(binding.getValue()); 113 | items.onNext("Alpha"); 114 | assertEquals("Alpha", binding.getValue()); 115 | items.onNext(nil); 116 | assertNull(binding.getValue()); 117 | latch.countDown(); 118 | }); 119 | 120 | try { 121 | latch.await(); 122 | } catch (InterruptedException e) { 123 | e.printStackTrace(); 124 | } 125 | } 126 | 127 | @Test 128 | public void testObserverNullableBinding() { 129 | final CountDownLatch latch = new CountDownLatch(1); 130 | Platform.runLater(() -> { 131 | 132 | PublishSubject> items = PublishSubject.create(); 133 | Binding binding = JavaFxObserver.toNullableBinding(items); 134 | items.onNext(Optional.empty()); 135 | 136 | assertNull(binding.getValue()); 137 | items.onNext(Optional.of("Alpha")); 138 | assertEquals("Alpha", binding.getValue()); 139 | items.onNext(Optional.empty()); 140 | assertNull(binding.getValue()); 141 | latch.countDown(); 142 | }); 143 | 144 | try { 145 | latch.await(); 146 | } catch (InterruptedException e) { 147 | e.printStackTrace(); 148 | } 149 | } 150 | 151 | @Test 152 | public void testObserverLazyBinding() { 153 | final CountDownLatch latch = new CountDownLatch(1); 154 | Platform.runLater(() -> { 155 | 156 | final AtomicInteger emissionCount = new AtomicInteger(0); 157 | 158 | Observable items = Observable.just("Alpha", "Beta", "Gamma", "Delta") 159 | .doOnNext(s -> emissionCount.incrementAndGet()); 160 | 161 | Binding binding = JavaFxObserver.toLazyBinding(items); 162 | 163 | sleep(1000); 164 | 165 | assertEquals(0, emissionCount.get()); 166 | 167 | binding.getValue(); 168 | 169 | sleep(1000); 170 | 171 | assertEquals(4, emissionCount.get()); 172 | assertEquals("Delta", binding.getValue()); 173 | latch.countDown(); 174 | }); 175 | 176 | try { 177 | latch.await(); 178 | } catch (InterruptedException e) { 179 | e.printStackTrace(); 180 | } 181 | } 182 | 183 | @Test 184 | public void testSubscriberNullBinding() { 185 | final CountDownLatch latch = new CountDownLatch(1); 186 | Platform.runLater(() -> { 187 | 188 | String nil = "null"; 189 | PublishProcessor items = PublishProcessor.create(); 190 | Binding binding = JavaFxSubscriber.toNullBinding(items, nil); 191 | items.onNext(nil); 192 | 193 | assertNull(binding.getValue()); 194 | items.onNext("Alpha"); 195 | assertEquals("Alpha", binding.getValue()); 196 | items.onNext(nil); 197 | assertNull(binding.getValue()); 198 | latch.countDown(); 199 | }); 200 | 201 | try { 202 | latch.await(); 203 | } catch (InterruptedException e) { 204 | e.printStackTrace(); 205 | } 206 | } 207 | 208 | @Test 209 | public void testSubscriberNullableBinding() { 210 | final CountDownLatch latch = new CountDownLatch(1); 211 | Platform.runLater(() -> { 212 | 213 | PublishProcessor> items = PublishProcessor.create(); 214 | Binding binding = JavaFxSubscriber.toNullableBinding(items); 215 | items.onNext(Optional.empty()); 216 | 217 | assertNull(binding.getValue()); 218 | items.onNext(Optional.of("Alpha")); 219 | assertEquals("Alpha", binding.getValue()); 220 | items.onNext(Optional.empty()); 221 | assertNull(binding.getValue()); 222 | latch.countDown(); 223 | }); 224 | 225 | try { 226 | latch.await(); 227 | } catch (InterruptedException e) { 228 | e.printStackTrace(); 229 | } 230 | } 231 | 232 | @Test 233 | public void testSubscriberBinding() { 234 | final CountDownLatch latch = new CountDownLatch(1); 235 | Platform.runLater(() -> { 236 | 237 | final AtomicInteger emissionCount = new AtomicInteger(0); 238 | 239 | Flowable items = Flowable.just("Alpha", "Beta", "Gamma", "Delta") 240 | .doOnNext(s -> emissionCount.incrementAndGet()); 241 | 242 | Binding binding = JavaFxSubscriber.toBinding(items); 243 | 244 | assertEquals(4, emissionCount.get()); 245 | assertEquals("Delta", binding.getValue()); 246 | latch.countDown(); 247 | }); 248 | 249 | try { 250 | latch.await(); 251 | } catch (InterruptedException e) { 252 | e.printStackTrace(); 253 | } 254 | } 255 | 256 | @Test 257 | public void testSubscriberLazyBinding() { 258 | final CountDownLatch latch = new CountDownLatch(1); 259 | Platform.runLater(() -> { 260 | 261 | final AtomicInteger emissionCount = new AtomicInteger(0); 262 | 263 | Flowable items = Flowable.just("Alpha", "Beta", "Gamma", "Delta") 264 | .doOnNext(s -> emissionCount.incrementAndGet()); 265 | 266 | Binding binding = JavaFxSubscriber.toLazyBinding(items); 267 | 268 | sleep(1000); 269 | 270 | assertEquals(0, emissionCount.get()); 271 | 272 | binding.getValue(); 273 | 274 | sleep(1000); 275 | 276 | assertEquals(4, emissionCount.get()); 277 | assertEquals("Delta", binding.getValue()); 278 | latch.countDown(); 279 | }); 280 | 281 | try { 282 | latch.await(); 283 | } catch (InterruptedException e) { 284 | e.printStackTrace(); 285 | } 286 | } 287 | 288 | private static void sleep(int millis) { 289 | try { 290 | Thread.sleep(millis); 291 | } catch (InterruptedException e) { 292 | e.printStackTrace(); 293 | } 294 | } 295 | } 296 | --------------------------------------------------------------------------------