├── .atlassian └── OWNER ├── .github └── workflows │ └── build.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── build.gradle ├── flowbius ├── build.gradle ├── gradle.properties └── src │ ├── main │ └── kotlin │ │ └── com │ │ └── trello │ │ └── flowbius │ │ ├── DiscardAfterDisposeConnectable.kt │ │ ├── EffectHandlerException.kt │ │ ├── FlowConnectables.kt │ │ ├── FlowDisposable.kt │ │ ├── FlowEventSources.kt │ │ ├── FlowMobius.kt │ │ ├── FlowMobiusEffectRouter.kt │ │ ├── FlowMobiusLoop.kt │ │ ├── MergedFlowTransformer.kt │ │ ├── UnknownEffectException.kt │ │ ├── UnrecoverableIncomingException.kt │ │ └── types.kt │ └── test │ └── kotlin │ └── com │ └── trello │ └── flowbius │ ├── DiscardAfterDisposeConnectableTest.kt │ ├── EffectHandlerExceptionTest.kt │ ├── FlowConnectablesKtTest.kt │ ├── FlowEventSourcesKtTest.kt │ ├── FlowMobiusEffectRouterTest.kt │ └── FlowMobiusLoopTest.kt ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.atlassian/OWNER: -------------------------------------------------------------------------------- 1 | [vrajeevan] -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | contents: read 10 | packages: write 11 | 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: Validate Gradle wrapper 16 | uses: gradle/wrapper-validation-action@v1 17 | 18 | - name: Set up JDK 11 19 | uses: actions/setup-java@v2 20 | with: 21 | java-version: '11' 22 | distribution: 'temurin' 23 | cache: gradle 24 | 25 | - name: Build with Gradle 26 | uses: gradle/gradle-build-action@v2.4.2 27 | with: 28 | arguments: build -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out/ 2 | 3 | ## Jetbrains 4 | 5 | .idea/ 6 | 7 | ## Gradle 8 | 9 | .gradle 10 | **/build/ 11 | !src/**/build/ 12 | 13 | # Ignore Gradle GUI config 14 | gradle-app.setting 15 | 16 | # Cache of project 17 | .gradletasknamecache 18 | 19 | # Eclipse Gradle plugin generated files 20 | # Eclipse Core 21 | .project 22 | # JDT-specific (Eclipse Java Development Tools) 23 | .classpath 24 | 25 | ## Java 26 | 27 | # Compiled class file 28 | *.class 29 | 30 | # Log file 31 | *.log 32 | 33 | # BlueJ files 34 | *.ctxt 35 | 36 | # Mobile Tools for Java (J2ME) 37 | .mtj.tmp/ 38 | 39 | # Package Files # 40 | *.jar 41 | *.war 42 | *.nar 43 | *.ear 44 | *.zip 45 | *.tar.gz 46 | *.rar 47 | 48 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 49 | !gradle-wrapper.jar 50 | 51 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 52 | hs_err_pid* 53 | replay_pid* -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | ## Version 0.1.3 4 | _2024-04-10 5 | 6 | * Fixes an issue in `FlowConnectable` that could emit data before the subscribing flow is complete, potentially dropping data. 7 | 8 | ## Version 0.1.2 9 | 10 | * Equal to 0.1.1, prefer to upgrade to 0.1.3, or continue using 0.1.1 11 | 12 | ## Version 0.1.1 13 | 14 | _2022-10-27_ 15 | 16 | * Fixed an issue where we could drop inital events: https://github.com/atlassian-labs/Flowbius/pull/7 17 | * Fixed an issue where we didn't declare the correct compatability: https://github.com/atlassian-labs/Flowbius/pull/9 18 | 19 | ## Version 0.1.0 20 | 21 | _2022-02-07_ 22 | 23 | * Initial release 24 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic addresses, without explicit permission 14 | * Submitting contributions or comments that you know to violate the intellectual property or privacy rights of others 15 | * Other unethical or unprofessional conduct 16 | 17 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 18 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 19 | 20 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 21 | 22 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer. Complaints will result in a response and be reviewed and investigated in a way that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. 23 | 24 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] 25 | 26 | [homepage]: http://contributor-covenant.org 27 | [version]: http://contributor-covenant.org/version/1/3/0/ -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Flowbius 2 | 3 | Thank you for considering a contribution to Flowbius! Pull requests, issues and comments are welcome. For pull requests, please: 4 | 5 | * Add tests for new features and bug fixes 6 | * Follow the existing style 7 | * Separate unrelated changes into multiple pull requests 8 | 9 | See the existing issues for things to start contributing. 10 | 11 | For bigger changes, please make sure you start a discussion first by creating an issue and explaining the intended change. 12 | 13 | Atlassian requires contributors to sign a Contributor License Agreement, known as a CLA. This serves as a record stating that the contributor is entitled to contribute the code/documentation/translation to the project and is willing to have it used in distributions and derivative works (or is willing to transfer ownership). 14 | 15 | Prior to accepting your contributions we ask that you please follow the appropriate link below to digitally sign the CLA. The Corporate CLA is for those who are contributing as a member of an organization and the individual CLA is for those contributing as an individual. 16 | 17 | * [CLA for corporate contributors](https://opensource.atlassian.com/corporate) 18 | * [CLA for individuals](https://opensource.atlassian.com/individual) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Atlassian Pty Ltd 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Flowbius 2 | 3 | [![Atlassian license](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=flat-square)](LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](CONTRIBUTING.md) 4 | 5 | Flowbius provides interoperability extensions for using [Kotlin Flows](https://kotlinlang.org/docs/flow.html) with [Mobius](https://github.com/spotify/mobius). They allow conversion from Flows to Mobius types and vice versa, as well as utilities to setup Mobius loops using Flows. 6 | 7 | Flowbius is analogous to what `mobius-rx` provides for RxJava/Mobius interoperability. 8 | 9 | ## Usage 10 | 11 | Flowbius provides converters from Flow types to Mobius types: 12 | 13 | ```kotlin 14 | // Flow -> EventSource 15 | val eventSource = flowOf(1, 2, 3).asEventSource() 16 | 17 | // EventSource -> Flow 18 | val flow = eventSource.asFlow() 19 | 20 | // FlowTransformer -> Connectable 21 | val connectable = { source: Flow -> source.map { it.length } }.asConnectable() 22 | 23 | // Apply a Connectable to a Flow as a flatMap which merges emissions 24 | val transformedFlow = flow.flatMapMerge(connectable) 25 | ``` 26 | 27 | You can also create a Mobius loop with Flow-based subtype effect handler: 28 | 29 | ```kotlin 30 | val loop = FlowMobius.loop( 31 | update = UpdateLogic(), 32 | effectHandler = subtypeEffectHandler { 33 | addConsumer(::handleEffects) 34 | addFunction(::effectToEvents) 35 | } 36 | ).startFrom(Model()) 37 | ``` 38 | 39 | ## Installation 40 | 41 | You can retrieve Flowbius from [Maven Central](https://search.maven.org/artifact/com.trello.flowbius/flowbius). 42 | 43 | ``` 44 | implementation 'com.trello.flowbius:flowbius:0.1.3' 45 | ``` 46 | 47 | ## Tests 48 | 49 | ``` 50 | $ ./gradlew tests 51 | ``` 52 | 53 | ## Contributions 54 | 55 | Contributions to Flowbius are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details. 56 | 57 | ## License 58 | 59 | Copyright (c) 2022 Atlassian and others. 60 | Apache 2.0 licensed, see [LICENSE](LICENSE) file. 61 | 62 |
63 | 64 | [![With ❤️ from Atlassian](https://raw.githubusercontent.com/atlassian-internal/oss-assets/master/banner-cheers.png)](https://www.atlassian.com) -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | Releasing 2 | ========= 3 | 4 | 1. Change the version in `gradle.properties` to a non-SNAPSHOT verson. 5 | 2. Update the `CHANGELOG.md` for the impending release. 6 | 3. Update the `README.md` with the new version. 7 | 4. `git commit -am "Prepare for release X.Y.Z."` (where X.Y.Z is the new version) 8 | 5. `./gradlew clean publishAllPublicationsToMavenCentralRepository`. 9 | 6. Visit [Sonatype Nexus](https://oss.sonatype.org/) and promote the artifact. 10 | 7. `git tag -a X.Y.Z -m "Version X.Y.Z"` (where X.Y.Z is the new version) 11 | 8. Update the `gradle.properties` to the next SNAPSHOT version. 12 | 9. `git commit -am "Prepare next development version."` 13 | 10. `git push && git push --tags` 14 | 11. Open a PR. 15 | 16 | 17 | Prerequisites 18 | ------------- 19 | 20 | In `~/.gradle/gradle.properties`, set the following: 21 | 22 | * `mavenCentralUsername` - Sonatype username for releasing to `com.trello`. 23 | * `mavenCentralPassword` - Sonatype password for releasing to `com.trello`. -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | } 6 | 7 | group 'com.trello.flowbius' 8 | version '0.1.3-SNAPSHOT' 9 | -------------------------------------------------------------------------------- /flowbius/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.kotlin.jvm) 3 | alias(libs.plugins.gradle.maven.publish.plugin) 4 | } 5 | 6 | compileKotlin { 7 | kotlinOptions.jvmTarget = '1.8' 8 | } 9 | 10 | compileTestKotlin { 11 | kotlinOptions.jvmTarget = '1.8' 12 | } 13 | 14 | java { 15 | sourceCompatibility = JavaVersion.VERSION_1_8 16 | targetCompatibility = JavaVersion.VERSION_1_8 17 | } 18 | 19 | repositories { 20 | mavenCentral() 21 | } 22 | 23 | dependencies { 24 | implementation libs.kotlin.stdlib 25 | implementation libs.kotlinx.coroutines 26 | 27 | api libs.mobius.core 28 | testImplementation libs.mobius.test 29 | 30 | testImplementation libs.junit 31 | 32 | testImplementation libs.turbine 33 | 34 | testImplementation libs.kotlinx.coroutines.test 35 | } 36 | -------------------------------------------------------------------------------- /flowbius/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=flowbius 2 | SONATYPE_HOST=DEFAULT 3 | RELEASE_SIGNING_ENABLED=true -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/DiscardAfterDisposeConnectable.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.Connectable 4 | import com.spotify.mobius.Connection 5 | import com.spotify.mobius.disposables.CompositeDisposable 6 | import com.spotify.mobius.disposables.Disposable 7 | import com.spotify.mobius.functions.Consumer 8 | 9 | /** 10 | * A [Connectable] that ensures that [Connection]s created by the wrapped [Connectable] don't emit or receive any 11 | * values after being disposed. 12 | * 13 | * This only acts as a safeguard, you still need to make sure that the Connectable disposes of resources correctly. 14 | */ 15 | internal class DiscardAfterDisposeConnectable(private val actual: Connectable) : Connectable { 16 | 17 | override fun connect(output: Consumer): Connection { 18 | val safeOutput = output.discardAfterDispose() 19 | val input = actual.connect(safeOutput) 20 | val safeInput = input.discardAfterDispose() 21 | 22 | val disposable = CompositeDisposable.from(safeInput, safeOutput) 23 | 24 | return object : Connection { 25 | override fun accept(effect: I) = safeInput.accept(effect) 26 | override fun dispose() = disposable.dispose() 27 | } 28 | } 29 | 30 | /** 31 | * Wraps a [Connection] or a [Consumer] and blocks them from receiving any further 32 | * values after the wrapper has been disposed. 33 | */ 34 | private class DiscardAfterDisposeWrapper( 35 | private val consumer: Consumer, 36 | private val disposable: Disposable? 37 | ) : Consumer, Disposable { 38 | 39 | @Volatile 40 | private var disposed = false 41 | 42 | override fun accept(effect: I) { 43 | if (!disposed) { 44 | consumer.accept(effect) 45 | } 46 | } 47 | 48 | override fun dispose() { 49 | disposed = true 50 | disposable?.dispose() 51 | } 52 | } 53 | 54 | private fun Connection.discardAfterDispose() = DiscardAfterDisposeWrapper(this, this) 55 | 56 | private fun Consumer.discardAfterDispose() = DiscardAfterDisposeWrapper(this, null) 57 | 58 | } -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/EffectHandlerException.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.ConnectionException 4 | 5 | class EffectHandlerException internal constructor(throwable: Throwable) : 6 | ConnectionException("Error in effect handler", throwable) { 7 | internal companion object { 8 | fun createFromEffectHandler(effectHandler: Any, cause: Throwable): EffectHandlerException { 9 | val e = EffectHandlerException(cause) 10 | val stackTrace = e.stackTrace 11 | 12 | // add a synthetic StackTraceElement so that the effect handler class name will be reported in 13 | // the exception. This helps troubleshooting where the issue originated from. 14 | stackTrace[0] = StackTraceElement(effectHandler::class.java.name, "apply", null, -1) 15 | 16 | e.stackTrace = stackTrace 17 | 18 | return e 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowConnectables.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.Connectable 4 | import com.spotify.mobius.Connection 5 | import com.spotify.mobius.functions.Consumer 6 | import kotlinx.coroutines.* 7 | import kotlinx.coroutines.channels.* 8 | import kotlinx.coroutines.flow.* 9 | import kotlinx.coroutines.sync.Mutex 10 | import kotlinx.coroutines.sync.withLock 11 | import kotlin.coroutines.CoroutineContext 12 | import kotlin.coroutines.EmptyCoroutineContext 13 | 14 | /** Generates a [Connectable] from a Flow map */ 15 | fun FlowTransformer.asConnectable(context: CoroutineContext = EmptyCoroutineContext): Connectable { 16 | return DiscardAfterDisposeConnectable(FlowConnectable(context, this)) 17 | } 18 | 19 | private class FlowConnectable( 20 | private val context: CoroutineContext, 21 | private val mapper: FlowTransformer 22 | ) : Connectable { 23 | override fun connect(output: Consumer): Connection { 24 | val sharedFlow = MutableSharedFlow(replay = 0, extraBufferCapacity = Int.MAX_VALUE) 25 | 26 | val connectableJob = Job() 27 | val connectableScope = CoroutineScope(connectableJob + Dispatchers.Unconfined + context) 28 | 29 | connectableScope.launch(start = CoroutineStart.ATOMIC) { 30 | sharedFlow 31 | .run { 32 | mapper(this) 33 | } 34 | .collect { output.accept(it) } 35 | } 36 | 37 | return object : Connection { 38 | private val exceptionHandler = CoroutineExceptionHandler { _, throwable -> 39 | if (throwable is NoSuchElementException) { 40 | // flow was cancelled before receiving a subscriber, no need to handle 41 | } else { 42 | throw throwable 43 | } 44 | } 45 | 46 | override fun accept(value: I) { 47 | connectableScope.launch(exceptionHandler) { 48 | // Wait for a subscription before emitting! 49 | sharedFlow.subscriptionCount.first { it > 0 } 50 | sharedFlow.emit(value) 51 | } 52 | } 53 | 54 | override fun dispose() { 55 | connectableJob.cancel() 56 | } 57 | } 58 | } 59 | } 60 | 61 | /** Applies the [Connectable]'s logic to go from Flow -> Flow */ 62 | @ExperimentalCoroutinesApi 63 | fun Flow.flatMapMerge(connectable: Connectable): Flow = callbackFlow { 64 | val wrappedConnectable = Connectable { output -> 65 | CloseChannelConnection(connectable.connect(output), channel) 66 | } 67 | 68 | val connection = wrappedConnectable.connect { output -> 69 | try { 70 | trySendBlocking(output).onFailure { throw it!! } 71 | } catch (e: InterruptedException) { 72 | // EventSource interrupts the source 73 | } 74 | } 75 | 76 | onCompletion { channel.close() } 77 | .collect { connection.accept(it) } 78 | 79 | awaitClose { connection.dispose() } 80 | } 81 | 82 | /** [Connection] wrapper that calls [SendChannel.close] upon disposal */ 83 | private class CloseChannelConnection( 84 | private val delegate: Connection, 85 | private val channel: SendChannel 86 | ) : Connection { 87 | override fun accept(value: I) = delegate.accept(value) 88 | 89 | override fun dispose() { 90 | delegate.dispose() 91 | channel.close() 92 | } 93 | } -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowDisposable.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.disposables.Disposable 4 | import kotlinx.coroutines.Job 5 | 6 | internal class FlowDisposable(private val job: Job) : Disposable { 7 | override fun dispose() { 8 | job.cancel() 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowEventSources.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.EventSource 4 | import com.spotify.mobius.functions.Consumer 5 | import kotlinx.coroutines.* 6 | import kotlinx.coroutines.channels.awaitClose 7 | import kotlinx.coroutines.channels.onFailure 8 | import kotlinx.coroutines.channels.trySendBlocking 9 | import kotlinx.coroutines.flow.Flow 10 | import kotlinx.coroutines.flow.callbackFlow 11 | import kotlinx.coroutines.flow.collect 12 | import kotlin.coroutines.CoroutineContext 13 | import kotlin.coroutines.EmptyCoroutineContext 14 | 15 | /** 16 | * Converts the given [Flow] to an [EventSource]. 17 | * 18 | * @param context an optional context that controls the execution context of calls to [Consumer] methods. 19 | * @param E the event type 20 | * @return an [EventSource] based on the provided [Flow] 21 | */ 22 | @ExperimentalCoroutinesApi 23 | fun Flow.asEventSource(context: CoroutineContext = EmptyCoroutineContext): EventSource = 24 | EventSource { eventConsumer -> 25 | val job = GlobalScope.launch(Dispatchers.Unconfined + context, start = CoroutineStart.ATOMIC) { 26 | collect(eventConsumer::accept) 27 | } 28 | 29 | return@EventSource FlowDisposable(job) 30 | } 31 | 32 | /** 33 | * Converts the given [EventSource] to a [Flow]. 34 | * 35 | * @param E the event type 36 | * @return a [Flow] based on the provided [EventSource] 37 | */ 38 | @ExperimentalCoroutinesApi 39 | fun EventSource.asFlow(): Flow = callbackFlow { 40 | val eventConsumer = Consumer { event -> 41 | try { 42 | trySendBlocking(event).onFailure { throw it!! } 43 | } catch (e: InterruptedException) { 44 | // EventSource interrupts the source 45 | } 46 | } 47 | 48 | val disposable = subscribe(eventConsumer) 49 | awaitClose { disposable.dispose() } 50 | } 51 | -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowMobius.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.Mobius 4 | import com.spotify.mobius.MobiusLoop 5 | import com.spotify.mobius.Update 6 | import com.spotify.mobius.functions.Consumer 7 | import com.spotify.mobius.functions.Function 8 | import kotlinx.coroutines.flow.* 9 | import kotlin.coroutines.CoroutineContext 10 | import kotlin.coroutines.EmptyCoroutineContext 11 | 12 | /** Factory methods for wrapping Mobius core classes in Flow transformers. */ 13 | object FlowMobius { 14 | 15 | /** 16 | * Create a [MobiusLoop.Builder] to help you configure a [MobiusLoop] before starting it. 17 | * 18 | * @param update the [Update] function of the loop 19 | * @param effectHandler the Flow-based effect handler of the loop 20 | * @param context optional [CoroutineContext] to control the execution context of the effect handler 21 | * @param [M] the model type 22 | * @param [E] the event type 23 | * @param [F] the effect type 24 | * @return a [MobiusLoop.Builder] instance that you can further configure before starting the loop 25 | */ 26 | fun loop( 27 | update: Update, 28 | context: CoroutineContext = EmptyCoroutineContext, 29 | effectHandler: FlowTransformer 30 | ): MobiusLoop.Builder = Mobius.loop(update, effectHandler.asConnectable(context)) 31 | 32 | /** 33 | * Create a [FlowTransformer] that starts from a given model. 34 | * 35 | * Every time the resulting Flow is subscribed to, a new [MobiusLoop] will be started from 36 | * the given model. 37 | * 38 | * @param loopFactory gets invoked for each subscription, to create a new MobiusLoop instance 39 | * @param startModel the starting point for each new loop 40 | * @param M the model type 41 | * @param E the event type 42 | * @param F the effect type 43 | * @return a transformer from event to model that you can connect to your UI 44 | */ 45 | fun loopFrom( 46 | loopFactory: MobiusLoop.Factory, 47 | startModel: M, 48 | startEffects: Set? = null 49 | ): FlowTransformer = FlowMobiusLoop(loopFactory, startModel, startEffects) 50 | 51 | /** 52 | * Builder for a type-routing effect handler. 53 | * 54 | * Register handlers for different subtypes of [F] using the [add] methods, and call [build] 55 | * to create an instance of the effect handler. You can then create a loop with the 56 | * router as the effect handler using [loop]. 57 | * 58 | * The handler will look at the type of each incoming effect object and try to find a 59 | * registered handler for that particular subtype of [F]. If a handler is found, it will be given 60 | * the effect object, otherwise an exception will be thrown. 61 | * 62 | * All the classes that the effect router know about must have a common type [F]. Note that 63 | * instances of the builder are mutable and not thread-safe. 64 | */ 65 | class SubtypeEffectHandlerBuilder internal constructor() { 66 | 67 | private val effectPerformerMap = mutableMapOf, FlowTransformer>() 68 | 69 | private var fatalErrorHandler: (suspend (Any, Throwable) -> Unit)? = null 70 | 71 | inline fun addAction(crossinline action: suspend () -> Unit) { 72 | addTransformer(G::class.java) { source -> 73 | source 74 | .onEach { action() } 75 | .mapNotNull { null } // Do not emit anything 76 | } 77 | } 78 | 79 | inline fun addConsumer(consumer: Consumer) { 80 | addConsumer { consumer.accept(it) } 81 | } 82 | 83 | inline fun addConsumer(noinline consumer: suspend (G) -> Unit) { 84 | addTransformer(G::class.java) { source -> 85 | source 86 | .onEach(consumer) 87 | .mapNotNull { null } // Do not emit anything 88 | } 89 | } 90 | 91 | inline fun addFunction(function: Function) { 92 | addFunction { function.apply(it) } 93 | } 94 | 95 | inline fun addFunction(noinline function: suspend (G) -> E) { 96 | addTransformer(G::class.java) { source -> 97 | source.map(function) 98 | } 99 | } 100 | 101 | inline fun addTransformer(noinline effectHandler: FlowTransformer) { 102 | addTransformer(G::class.java, effectHandler) 103 | } 104 | 105 | fun addTransformer( 106 | effectClass: Class, 107 | effectHandler: FlowTransformer 108 | ): SubtypeEffectHandlerBuilder = apply { 109 | requireNoEffectCollisions(effectClass) 110 | 111 | effectPerformerMap[effectClass] = { effects -> 112 | effects 113 | .filterIsInstance(effectClass) 114 | .run(effectHandler) 115 | .catch { e -> 116 | fatalErrorHandler?.invoke(effectHandler, e) 117 | ?: throw EffectHandlerException.createFromEffectHandler(effectHandler, e) 118 | 119 | // If we did custom handling, re-throw (provided they did not already do it) 120 | throw e 121 | } 122 | } 123 | } 124 | 125 | private fun requireNoEffectCollisions(effectClass: Class) { 126 | effectPerformerMap.keys.forEach { cls -> 127 | require(!cls.isAssignableFrom(effectClass) && !effectClass.isAssignableFrom(cls)) { 128 | "Effect classes may not be assignable to each other, collision found: " + 129 | "${effectClass.simpleName} <-> ${cls.simpleName}" 130 | } 131 | } 132 | } 133 | 134 | fun withFatalErrorHandler(fatalErrorHandler: (suspend (Any, Throwable) -> Unit)) = apply { 135 | this.fatalErrorHandler = fatalErrorHandler 136 | } 137 | 138 | internal fun build(): FlowTransformer { 139 | return FlowMobiusEffectRouter(effectPerformerMap.keys, effectPerformerMap.values) 140 | } 141 | 142 | /** Version of [filterIsInstance] that works with non-reified [Class] references */ 143 | @Suppress("UNCHECKED_CAST") 144 | private fun Flow.filterIsInstance(clazz: Class) = filter { clazz.isInstance(it) } as Flow 145 | } 146 | } 147 | 148 | /** 149 | * Use this builder to configure [FlowMobius.SubtypeEffectHandlerBuilder]. 150 | */ 151 | fun subtypeEffectHandler( 152 | configure: FlowMobius.SubtypeEffectHandlerBuilder.() -> Unit 153 | ): FlowTransformer = FlowMobius.SubtypeEffectHandlerBuilder().apply(configure).build() 154 | -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowMobiusEffectRouter.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import kotlinx.coroutines.flow.Flow 4 | import kotlinx.coroutines.flow.filter 5 | import kotlinx.coroutines.flow.map 6 | import java.util.* 7 | 8 | internal class FlowMobiusEffectRouter( 9 | handledEffectClasses: Set>, 10 | effectPerformers: Collection> 11 | ) : FlowTransformer { 12 | 13 | private val effectClasses: Set> = Collections.unmodifiableSet(handledEffectClasses) 14 | 15 | private val mergedTransformer = MergedFlowTransformer( 16 | Collections.unmodifiableList(effectPerformers.toList() + ::unhandledEffectHandler) 17 | ) 18 | 19 | private fun unhandledEffectHandler(source: Flow): Flow { 20 | return source 21 | .filter { effect -> effectClasses.none { effectClass -> effectClass.isAssignableFrom(effect::class.java) } } 22 | .map { throw UnknownEffectException(it) } 23 | } 24 | 25 | override fun invoke(source: Flow): Flow = source.run(mergedTransformer) 26 | 27 | } -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/FlowMobiusLoop.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.MobiusLoop 4 | import kotlinx.coroutines.ExperimentalCoroutinesApi 5 | import kotlinx.coroutines.channels.awaitClose 6 | import kotlinx.coroutines.channels.onFailure 7 | import kotlinx.coroutines.channels.trySendBlocking 8 | import kotlinx.coroutines.flow.* 9 | 10 | @ExperimentalCoroutinesApi 11 | internal class FlowMobiusLoop( 12 | private val loopFactory: MobiusLoop.Factory, 13 | private val startModel: M, 14 | private val startEffects: Set? 15 | ) : FlowTransformer { 16 | override fun invoke(events: Flow): Flow = callbackFlow { 17 | val loop = if (startEffects.isNullOrEmpty()) loopFactory.startFrom(startModel) 18 | else loopFactory.startFrom(startModel, startEffects) 19 | 20 | loop.observe { newModel -> 21 | try { 22 | trySendBlocking(newModel).onFailure { throw it!! } 23 | } catch (e: InterruptedException) { 24 | // EventSource interrupts the source 25 | } 26 | } 27 | 28 | events 29 | .onCompletion { channel.close() } 30 | .catch { throwable -> throw UnrecoverableIncomingException(throwable) } 31 | .collect { event -> loop.dispatchEvent(event) } 32 | 33 | awaitClose { 34 | loop.dispose() 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/MergedFlowTransformer.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import kotlinx.coroutines.flow.Flow 4 | import kotlinx.coroutines.flow.merge 5 | 6 | internal class MergedFlowTransformer( 7 | private val transformers: Iterable> 8 | ) : FlowTransformer { 9 | 10 | override fun invoke(source: Flow): Flow { 11 | return merge(*transformers.map { source.run(it) }.toTypedArray()) 12 | } 13 | } -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/UnknownEffectException.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | /** 4 | * Indicates that a [FlowMobiusEffectRouter] has received an effect that it hasn't received 5 | * configuration for. This is a programmer error. 6 | */ 7 | class UnknownEffectException internal constructor(internal val effect: Any) : RuntimeException(effect.toString()) -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/UnrecoverableIncomingException.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | /** 4 | * Used to indicate that an [FlowMobiusLoop] transformer has received a [Throwable], which is illegal. 5 | * This exception means Mobius is in an undefined state and should be considered a fatal programmer error. Do not try 6 | * to handle this exception in your code, ensure it never gets thrown. 7 | */ 8 | class UnrecoverableIncomingException internal constructor(throwable: Throwable) : RuntimeException( 9 | "PROGRAMMER ERROR: Mobius cannot recover from this exception; ensure your event sources don't throw exceptions", 10 | throwable 11 | ) 12 | -------------------------------------------------------------------------------- /flowbius/src/main/kotlin/com/trello/flowbius/types.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import kotlinx.coroutines.flow.Flow 4 | 5 | typealias FlowTransformer = (Flow) -> Flow 6 | -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/DiscardAfterDisposeConnectableTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import com.spotify.mobius.Connectable 4 | import com.spotify.mobius.Connection 5 | import com.spotify.mobius.functions.Consumer 6 | import com.spotify.mobius.test.RecordingConsumer 7 | import org.junit.Assert.assertTrue 8 | import org.junit.Test 9 | 10 | class DiscardAfterDisposeConnectableTest { 11 | 12 | @Test 13 | fun forwardsMessagesToWrappedConsumer() { 14 | val consumer = RecordingConsumer() 15 | val underlyingConnection = TestConnection(consumer) 16 | val connectable = DiscardAfterDisposeConnectable(Connectable { underlyingConnection }) 17 | val connection = connectable.connect(consumer) 18 | 19 | connection.accept(14) 20 | consumer.assertValues("Value is: 14") 21 | } 22 | 23 | @Test 24 | fun delegatesDisposeToActualConnection() { 25 | val consumer = RecordingConsumer() 26 | val underlyingConnection = TestConnection(consumer) 27 | val connectable = DiscardAfterDisposeConnectable(Connectable { underlyingConnection }) 28 | val connection = connectable.connect(consumer) 29 | 30 | connection.dispose() 31 | assertTrue(underlyingConnection.disposed) 32 | } 33 | 34 | @Test 35 | fun discardsEventsAfterDisposal() { 36 | val consumer = RecordingConsumer() 37 | val underlyingConnection = TestConnection(consumer) 38 | val connectable = DiscardAfterDisposeConnectable(Connectable { underlyingConnection }) 39 | val connection = connectable.connect(consumer) 40 | 41 | // given a disposed connection 42 | connection.dispose() 43 | 44 | // when a message arrives 45 | connection.accept(1) 46 | 47 | // it is discarded 48 | consumer.assertValues() 49 | } 50 | 51 | private class TestConnection(private val eventConsumer: Consumer) : Connection { 52 | @Volatile 53 | var disposed = false 54 | 55 | override fun accept(effect: Int) = eventConsumer.accept("Value is: $effect") 56 | 57 | override fun dispose() { 58 | disposed = true 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/EffectHandlerExceptionTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import org.junit.Assert.assertTrue 4 | import org.junit.Test 5 | 6 | class EffectHandlerExceptionTest { 7 | 8 | class PretendEffectHandler 9 | 10 | @Test 11 | fun shouldProvideAGoodStackTrace() { 12 | val cause = RuntimeException("hey") 13 | val effectHandlerException = EffectHandlerException.createFromEffectHandler(PretendEffectHandler(), cause) 14 | assertTrue(PretendEffectHandler::class.java.name in effectHandlerException.stackTraceToString()) 15 | assertTrue(effectHandlerException.cause == cause) 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/FlowConnectablesKtTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import app.cash.turbine.test 4 | import com.spotify.mobius.Connectable 5 | import com.spotify.mobius.Connection 6 | import com.spotify.mobius.test.RecordingConsumer 7 | import kotlinx.coroutines.* 8 | import kotlinx.coroutines.flow.* 9 | import kotlinx.coroutines.test.UnconfinedTestDispatcher 10 | import kotlinx.coroutines.test.advanceUntilIdle 11 | import kotlinx.coroutines.test.runTest 12 | import org.junit.Assert.assertEquals 13 | import org.junit.Test 14 | import java.util.concurrent.CyclicBarrier 15 | import java.util.concurrent.Executors 16 | import kotlin.time.ExperimentalTime 17 | 18 | @FlowPreview 19 | @ExperimentalCoroutinesApi 20 | @ExperimentalTime 21 | class FlowConnectablesKtTest { 22 | 23 | @Test 24 | fun asConnectable() { 25 | val consumer = RecordingConsumer() 26 | 27 | val transformer = { source: Flow -> source.flatMapConcat { flowOf(it.length, it.length * 2) } } 28 | val connectable = transformer.asConnectable() 29 | val connection = connectable.connect(consumer) 30 | 31 | // Verify we receive transformed values 32 | connection.accept("one") 33 | connection.accept("three") 34 | consumer.assertValues(3, 6, 5, 10) 35 | consumer.clearValues() 36 | 37 | // Verify that after disposing, we get no more values 38 | connection.dispose() 39 | assertEquals(0, consumer.valueCount()) 40 | } 41 | 42 | @Test 43 | fun awaitSubscriptions() = runTest(UnconfinedTestDispatcher()) { 44 | val consumer = RecordingConsumer() 45 | 46 | val transformer = { source: Flow -> source.flatMapConcat { flowOf(it.length, it.length * 2) } } 47 | val connectable = transformer.asConnectable() 48 | 49 | // Run in quick sequence to ensure we're waiting on the subscription to occur before emitting results 50 | val connection = async { 51 | val currentConnection = connectable.connect(consumer) 52 | currentConnection.accept("one") 53 | currentConnection.accept("three") 54 | currentConnection.accept("ten") 55 | currentConnection.accept("five") 56 | currentConnection 57 | } 58 | advanceUntilIdle() 59 | 60 | consumer.assertValues(3, 6, 5, 10, 3, 6, 4, 8) 61 | consumer.clearValues() 62 | 63 | // Verify that after disposing, we get no more values 64 | connection.await().dispose() 65 | assertEquals(0, consumer.valueCount()) 66 | } 67 | 68 | @Test 69 | fun asConnectable_handlesConcurrentConnections() { 70 | val numTrials = 15 71 | val pool = Executors.newCachedThreadPool() 72 | val barrier = CyclicBarrier(numTrials + 1) 73 | 74 | val consumer = RecordingConsumer() 75 | val transformer = { source: Flow -> source.map { it * it } } 76 | val connectable = transformer.asConnectable() 77 | val connection = connectable.connect(consumer) 78 | 79 | (1..numTrials).forEach { 80 | pool.execute { 81 | barrier.await() 82 | connection.accept(it) 83 | barrier.await() 84 | } 85 | } 86 | 87 | barrier.await() // wait for all threads to be ready 88 | barrier.await() // wait for all threads to finish 89 | 90 | consumer.assertValuesInAnyOrder(*(1..numTrials).map { it * it }.toTypedArray()) 91 | } 92 | 93 | @Test 94 | fun asConnectableCreatesIndependentConnections() { 95 | val consumer1 = RecordingConsumer() 96 | val consumer2 = RecordingConsumer() 97 | 98 | val transformer = { source: Flow -> source.flatMapConcat { flowOf(it.length, it.length * 2) } } 99 | val connectable = transformer.asConnectable() 100 | val connection1 = connectable.connect(consumer1) 101 | val connection2 = connectable.connect(consumer2) 102 | 103 | connection1.accept("one") 104 | connection1.dispose() 105 | 106 | connection2.accept("three") 107 | connection2.dispose() 108 | 109 | // Assert that the two connections do not pass values/state to each other by accident 110 | consumer1.assertValues(3, 6) 111 | consumer2.assertValues(5, 10) 112 | } 113 | 114 | @Test 115 | fun mapShouldPropagateCompletion() = runTest { 116 | val connectable = Connectable { output -> 117 | object : Connection { 118 | override fun accept(value: String) = output.accept(value.length) 119 | override fun dispose() {} 120 | } 121 | } 122 | 123 | flowOf("hi", "bye") 124 | .flatMapMerge(connectable) 125 | .test { 126 | assertEquals(2, awaitItem()) 127 | assertEquals(3, awaitItem()) 128 | awaitComplete() 129 | } 130 | } 131 | 132 | @Test 133 | fun mapShouldPropagateErrorsFromConnectable() = runTest { 134 | val crashingCollectable = Connectable { 135 | object : Connection { 136 | override fun accept(value: String) = error("crashing!") 137 | override fun dispose() = error("Should not be here in this test") 138 | } 139 | } 140 | 141 | flowOf("crash") 142 | .flatMapMerge(crashingCollectable) 143 | .test { assertEquals("crashing!", awaitError().message) } 144 | } 145 | 146 | @Test 147 | fun mapShouldPropagateErrorsFromUpstream() = runTest { 148 | val connectable = Connectable { output -> 149 | object : Connection { 150 | override fun accept(value: String) = output.accept(value.length) 151 | override fun dispose() {} 152 | } 153 | } 154 | 155 | flow { error("expected") } 156 | .flatMapMerge(connectable) 157 | .test { assertEquals("expected", awaitError().message) } 158 | } 159 | } -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/FlowEventSourcesKtTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import app.cash.turbine.test 4 | import com.spotify.mobius.EventSource 5 | import com.spotify.mobius.disposables.Disposable 6 | import com.spotify.mobius.functions.Consumer 7 | import com.spotify.mobius.test.RecordingConsumer 8 | import kotlinx.coroutines.CoroutineExceptionHandler 9 | import kotlinx.coroutines.flow.MutableSharedFlow 10 | import kotlinx.coroutines.flow.flow 11 | import kotlinx.coroutines.flow.flowOf 12 | import kotlinx.coroutines.runBlocking 13 | import org.junit.Assert.assertEquals 14 | import org.junit.Test 15 | import kotlin.time.ExperimentalTime 16 | 17 | @ExperimentalTime 18 | class FlowEventSourcesKtTest { 19 | 20 | @Test 21 | fun eventsAreForwardedInOrder() { 22 | val source = flowOf(1, 2, 3).asEventSource() 23 | val consumer = RecordingConsumer() 24 | 25 | source.subscribe(consumer) 26 | 27 | consumer.assertValues(1, 2, 3) 28 | } 29 | 30 | @Test 31 | fun disposePreventsFurtherEvents() { 32 | val sharedFlow = MutableSharedFlow() 33 | val source = sharedFlow.asEventSource() 34 | val consumer = RecordingConsumer() 35 | 36 | val d = source.subscribe(consumer) 37 | 38 | runBlocking { 39 | sharedFlow.emit(1) 40 | sharedFlow.emit(2) 41 | d.dispose() 42 | sharedFlow.emit(3) 43 | } 44 | 45 | consumer.assertValues(1, 2) 46 | } 47 | 48 | @Test 49 | fun errorsAreForwardedToErrorHandler() { 50 | var caughtException: Throwable? = null 51 | val exceptionHandler = CoroutineExceptionHandler { _, e -> caughtException = e } 52 | val sharedFlow = flow { throw RuntimeException("crash!") } 53 | val source = sharedFlow.asEventSource(exceptionHandler) 54 | val consumer = RecordingConsumer() 55 | 56 | source.subscribe(consumer) 57 | 58 | assertEquals("crash!", caughtException?.message) 59 | } 60 | 61 | @Test 62 | fun eventsToFlow() = runBlocking { 63 | val eventSource = TestEventSource() 64 | 65 | eventSource.asFlow().test { 66 | expectNoEvents() 67 | 68 | eventSource.accept(1) 69 | assertEquals(1, awaitItem()) 70 | 71 | eventSource.accept(2) 72 | assertEquals(2, awaitItem()) 73 | 74 | eventSource.accept(3) 75 | assertEquals(3, awaitItem()) 76 | } 77 | } 78 | 79 | @Test 80 | fun cancelPreventsFurtherFlowItems() = runBlocking { 81 | val eventSource = TestEventSource() 82 | 83 | eventSource.asFlow().test { 84 | expectNoEvents() 85 | 86 | eventSource.accept(1) 87 | assertEquals(1, awaitItem()) 88 | 89 | cancel() 90 | 91 | eventSource.accept(2) 92 | expectNoEvents() 93 | } 94 | } 95 | 96 | private class TestEventSource : EventSource { 97 | 98 | private val consumers = mutableListOf>() 99 | private var disposed = false 100 | 101 | override fun subscribe(eventConsumer: Consumer): Disposable { 102 | consumers += eventConsumer 103 | return Disposable { disposed = true } 104 | } 105 | 106 | fun accept(value: E) { 107 | if (!disposed) { 108 | consumers.forEach { it.accept(value) } 109 | } 110 | } 111 | } 112 | 113 | } -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/FlowMobiusEffectRouterTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import app.cash.turbine.test 4 | import com.spotify.mobius.functions.Function 5 | import com.spotify.mobius.test.RecordingConsumer 6 | import kotlinx.coroutines.flow.collect 7 | import kotlinx.coroutines.flow.flowOf 8 | import kotlinx.coroutines.flow.map 9 | import kotlinx.coroutines.runBlocking 10 | import org.junit.Assert.* 11 | import org.junit.Before 12 | import org.junit.Test 13 | import kotlin.time.ExperimentalTime 14 | 15 | @ExperimentalTime 16 | class FlowMobiusEffectRouterTest { 17 | 18 | private lateinit var consumer: RecordingConsumer 19 | private lateinit var action: TestAction 20 | private lateinit var router: FlowTransformer 21 | 22 | @Before 23 | fun setup() { 24 | consumer = RecordingConsumer() 25 | action = TestAction() 26 | router = subtypeEffectHandler { 27 | addTransformer { source -> source.map { TestEvent.A(it.id) } } 28 | addTransformer { source -> source.map { TestEvent.B(it.id) } } 29 | addConsumer(consumer) 30 | addAction(action::invoke) 31 | addFunction { e -> TestEvent.E(e.id) } 32 | addFunction(Function { value -> TestEvent.F(value.id) }) 33 | } 34 | } 35 | 36 | @Test 37 | fun shouldRouteEffectToPerformer() = runBlocking { 38 | flowOf(TestEffect.A(456)) 39 | .run(router) 40 | .test { 41 | assertEquals(TestEvent.A(456), awaitItem()) 42 | awaitComplete() 43 | } 44 | } 45 | 46 | @Test 47 | fun shouldRouteEffectToMobiusConsumer() = runBlocking { 48 | flowOf(TestEffect.C(456)) 49 | .run(router) 50 | .collect() 51 | 52 | consumer.assertValues(TestEffect.C(456)) 53 | } 54 | 55 | @Test 56 | fun shouldRouteEffectToConsumer() = runBlocking { 57 | flowOf(TestEffect.C(456)) 58 | .run(router) 59 | .collect() 60 | 61 | consumer.assertValues(TestEffect.C(456)) 62 | } 63 | 64 | @Test 65 | fun shouldRunActionOnConsumer() = runBlocking { 66 | var lastValue: TestEffect.C? = null 67 | 68 | flowOf(TestEffect.C(456)) 69 | .run(subtypeEffectHandler { 70 | addConsumer { lastValue = it } 71 | }) 72 | .collect() 73 | 74 | assertEquals(TestEffect.C(456), lastValue) 75 | } 76 | 77 | @Test 78 | fun shouldInvokeFunctionAndEmitEvent() = runBlocking { 79 | flowOf(TestEffect.E(123)) 80 | .run(router) 81 | .test { 82 | assertEquals(TestEvent.E(123), awaitItem()) 83 | awaitComplete() 84 | } 85 | } 86 | 87 | @Test 88 | fun shouldInvokeMobiusFunctionAndEmitEvent() = runBlocking { 89 | flowOf(TestEffect.F(123)) 90 | .run(router) 91 | .test { 92 | assertEquals(TestEvent.F(123), awaitItem()) 93 | awaitComplete() 94 | } 95 | } 96 | 97 | @Test 98 | fun shouldFailForUnhandledEffect() = runBlocking { 99 | flowOf(TestEffect.Unhandled) 100 | .run(router) 101 | .test { 102 | val error = awaitError() as UnknownEffectException 103 | assertEquals(TestEffect.Unhandled, error.effect) 104 | } 105 | } 106 | 107 | @Test 108 | fun shouldReportEffectClassCollisionWhenAddingSuperclass() { 109 | subtypeEffectHandler { 110 | addAction { } 111 | 112 | assertThrows(IllegalArgumentException::class.java) { 113 | addAction { } 114 | } 115 | } 116 | } 117 | 118 | @Test 119 | fun shouldReportEffectClassCollisionWhenAddingSubclass() { 120 | subtypeEffectHandler { 121 | addAction { } 122 | 123 | assertThrows(IllegalArgumentException::class.java) { 124 | addAction { } 125 | } 126 | } 127 | } 128 | 129 | @Test 130 | fun shouldSupportCustomErrorHandler() = runBlocking { 131 | val expectedException = RuntimeException("expected!") 132 | 133 | val router = subtypeEffectHandler { 134 | addFunction { throw expectedException } 135 | 136 | withFatalErrorHandler { _, throwable -> 137 | assertEquals(expectedException, throwable) 138 | } 139 | } 140 | 141 | flowOf(TestEffect.A(1)) 142 | .run(router) 143 | .test { 144 | val error = awaitError() 145 | assertTrue(error is RuntimeException) 146 | assertEquals("expected!", error.message) 147 | } 148 | } 149 | 150 | private class TestAction { 151 | var runCount = 0 152 | 153 | fun invoke() { 154 | runCount++ 155 | } 156 | } 157 | 158 | sealed class TestEffect { 159 | data class A(val id: Int) : TestEffect() 160 | data class B(val id: Int) : TestEffect() 161 | data class C(val id: Int) : TestEffect() 162 | data class D(val id: Int) : TestEffect() 163 | data class E(val id: Int) : TestEffect() 164 | data class F(val id: Int) : TestEffect() 165 | 166 | object Unhandled : TestEffect() 167 | 168 | open class Parent : TestEffect() 169 | object Child : Parent() 170 | } 171 | 172 | sealed class TestEvent { 173 | data class A(val id: Int) : TestEvent() 174 | data class B(val id: Int) : TestEvent() 175 | data class E(val id: Int) : TestEvent() 176 | data class F(val id: Int) : TestEvent() 177 | } 178 | 179 | } -------------------------------------------------------------------------------- /flowbius/src/test/kotlin/com/trello/flowbius/FlowMobiusLoopTest.kt: -------------------------------------------------------------------------------- 1 | package com.trello.flowbius 2 | 3 | import app.cash.turbine.test 4 | import com.spotify.mobius.Effects.effects 5 | import com.spotify.mobius.First.first 6 | import com.spotify.mobius.Mobius 7 | import com.spotify.mobius.Next.next 8 | import com.spotify.mobius.runners.ImmediateWorkRunner 9 | import com.spotify.mobius.test.RecordingConnection 10 | import com.spotify.mobius.test.RecordingConsumer 11 | import kotlinx.coroutines.Dispatchers 12 | import kotlinx.coroutines.delay 13 | import kotlinx.coroutines.flow.* 14 | import kotlinx.coroutines.launch 15 | import kotlinx.coroutines.runBlocking 16 | import org.junit.Assert.assertEquals 17 | import org.junit.Assert.assertTrue 18 | import org.junit.Test 19 | import kotlin.time.ExperimentalTime 20 | 21 | @ExperimentalTime 22 | class FlowMobiusLoopTest { 23 | 24 | @Test 25 | fun loop() = runBlocking { 26 | val recordingConsumer = RecordingConsumer() 27 | 28 | val loop = FlowMobius.loop( 29 | update = { model, event -> next(model + event.toString(), setOf(true)) }, 30 | effectHandler = subtypeEffectHandler { addConsumer(recordingConsumer) } 31 | ) 32 | .eventRunner(::ImmediateWorkRunner) 33 | .effectRunner(::ImmediateWorkRunner) 34 | .startFrom("Hello") 35 | 36 | assertEquals("Hello", loop.mostRecentModel) 37 | recordingConsumer.assertValues() 38 | 39 | loop.dispatchEvent(5) 40 | assertEquals("Hello5", loop.mostRecentModel) 41 | recordingConsumer.assertValues(true) 42 | } 43 | 44 | @Test 45 | fun startModelAndEffects() = runBlocking { 46 | val connection = RecordingConnection() 47 | val builder = Mobius.loop( 48 | { model, event -> next(model + event.toString()) }, 49 | { connection } 50 | ).effectRunner { ImmediateWorkRunner() } 51 | 52 | val loop = FlowMobius.loopFrom(builder, "StartModel", effects(true, false)) 53 | 54 | val events = MutableSharedFlow(extraBufferCapacity = 1) 55 | 56 | events 57 | .run(loop) 58 | .test { 59 | assertEquals("StartModel", awaitItem()) 60 | 61 | events.tryEmit(1) 62 | assertEquals("StartModel1", awaitItem()) 63 | } 64 | 65 | assertEquals(2, connection.valueCount()) 66 | connection.assertValuesInAnyOrder(true, false) 67 | } 68 | 69 | @Test 70 | fun shouldSupportStartingALoopWithAnInit() = runBlocking { 71 | val connection = RecordingConnection() 72 | val builder = Mobius.loop( 73 | { model, event -> next(model + event.toString()) }, 74 | { connection } 75 | ).init { model -> first("$model-init") } 76 | 77 | val loop = FlowMobius.loopFrom(builder, "hi") 78 | 79 | val events = MutableSharedFlow(extraBufferCapacity = 1) 80 | 81 | events 82 | .run(loop) 83 | .test { 84 | assertEquals("hi-init", awaitItem()) 85 | 86 | events.tryEmit(10) 87 | assertEquals("hi-init10", awaitItem()) 88 | } 89 | } 90 | 91 | @Test 92 | fun shouldThrowIfStartingALoopWithInitAndStartEffects() = runBlocking { 93 | val connection = RecordingConnection() 94 | val builder = Mobius.loop( 95 | { model, event -> next(model + event.toString()) }, 96 | { connection } 97 | ).init { model -> first("$model-init") } 98 | 99 | val loop = FlowMobius.loopFrom(builder, "hi", effects(true)) 100 | 101 | val events = MutableSharedFlow(extraBufferCapacity = 1) 102 | 103 | events 104 | .run(loop) 105 | .test { 106 | val error = awaitError() 107 | assertTrue(error is IllegalArgumentException) 108 | assertEquals("cannot pass in start effects when a loop has init defined", error.message) 109 | } 110 | } 111 | 112 | @Test 113 | fun shouldPropagateIncomingErrorsAsUnrecoverable() = runBlocking { 114 | val connection = RecordingConnection() 115 | val builder = Mobius.loop( 116 | { model, event -> next(model + event.toString()) }, 117 | { connection } 118 | ).effectRunner { ImmediateWorkRunner() } 119 | 120 | val loop = FlowMobius.loopFrom(builder, "") 121 | 122 | val events = flow { throw RuntimeException("expected") } 123 | 124 | events 125 | .run(loop) 126 | .test { 127 | // Initial model 128 | assertEquals("", awaitItem()) 129 | 130 | // Error 131 | val error = awaitError() 132 | assertTrue(error is UnrecoverableIncomingException) 133 | } 134 | 135 | assertEquals(0, connection.valueCount()) 136 | } 137 | 138 | /** 139 | * [Dispatchers.Unconfined] has unfortunate nested behavior for us, which is that its order of execution is undefined. 140 | * This can cause problems where start effects aren't ever handled because the start effect fires *before* the loop 141 | * is fully configured. This test verifies that we won't miss start effects in this situation. 142 | */ 143 | @Test 144 | fun startEffectWorksWithUnconfinedDispatchers() = runBlocking { 145 | data class LoadEffect(val id: String) 146 | data class LoadEvent(val id: String) 147 | 148 | val job = launch(Dispatchers.Unconfined) { 149 | val loop = FlowMobius.loop( 150 | update = { _, event -> next("Loaded data: ${event.id}") }, 151 | context = Dispatchers.Unconfined, 152 | effectHandler = subtypeEffectHandler { addTransformer { s -> s.map { LoadEvent(it.id) } } } 153 | ) 154 | .eventRunner(::ImmediateWorkRunner) 155 | .effectRunner(::ImmediateWorkRunner) 156 | .startFrom("No data loaded", setOf(LoadEffect("abc"))) 157 | 158 | // I hate to add this delay, but we have to give the loop a suspend point with which to initially process data. 159 | // 160 | // This implies that the start effect will not *immediately* fire off on loop startup, which is unfortunate 161 | // but unavoidable given what happens with scheduling nested Dispatchers.Unconfined launches. 162 | delay(10) 163 | 164 | assertEquals("Loaded data: abc", loop.mostRecentModel) 165 | } 166 | 167 | job.join() 168 | } 169 | 170 | /** 171 | * [Dispatchers.Unconfined] has unfortunate nested behavior for us, which is that its order of execution is undefined. 172 | * This can cause problems where start effects aren't ever handled because the start effect fires *before* the loop 173 | * is fully configured. This test verifies that we won't miss start effects in this situation. 174 | */ 175 | @Test 176 | fun startEffectWorksWithUnconfinedDispatchersWithFlatMap() = runBlocking { 177 | 178 | data class LoadEffect(val id: String) 179 | data class LoadEvent(val id: String) 180 | 181 | val job = launch(Dispatchers.Unconfined) { 182 | val loop = FlowMobius.loop( 183 | update = { _, event -> next("Loaded data: ${event.id}") }, 184 | context = Dispatchers.Unconfined, 185 | effectHandler = subtypeEffectHandler { addTransformer { s -> s.flatMapLatest { flowOf(LoadEvent(it.id)) } } } 186 | ) 187 | .eventRunner(::ImmediateWorkRunner) 188 | .effectRunner(::ImmediateWorkRunner) 189 | .startFrom("No data loaded", setOf(LoadEffect("abc"))) 190 | 191 | // I hate to add this delay, but we have to give the loop a suspend point with which to initially process data. 192 | // 193 | // This implies that the start effect will not *immediately* fire off on loop startup, which is unfortunate 194 | // but unavoidable given what happens with scheduling nested Dispatchers.Unconfined launches. 195 | delay(10) 196 | 197 | assertEquals("Loaded data: abc", loop.mostRecentModel) 198 | } 199 | 200 | job.join() 201 | } 202 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | 3 | GROUP=com.trello.flowbius 4 | VERSION_NAME=0.1.3-SNAPSHOT 5 | 6 | POM_NAME=Flowbius 7 | POM_DESCRIPTION=Kotlin Flow <-> Spotify Mobius interop 8 | POM_INCEPTION_YEAR=2022 9 | POM_URL=https://github.com/atlassian-labs/Flowbius 10 | 11 | POM_LICENSE_NAME=The Apache Software License, Version 2.0 12 | POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt 13 | POM_LICENSE_DIST=repo 14 | 15 | POM_SCM_URL=https://github.com/atlassian-labs/Flowbius/ 16 | POM_SCM_CONNECTION=scm:git:git://github.com/atlassian-labs/Flowbius.git 17 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/atlassian-labs/Flowbius.git 18 | 19 | POM_DEVELOPER_ID=atlassian-labs 20 | POM_DEVELOPER_NAME=Atlassian, Inc. 21 | POM_DEVELOPER_URL=https://github.com/atlassian-labs/ -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | # Because we use Mobius with Compose, we track the latest stable version of Kotlin compatible w/ Compose 3 | # For more info, see here: https://developer.android.com/jetpack/androidx/releases/compose-kotlin 4 | kotlin = "1.8.20" 5 | mobius = "1.5.12" 6 | coroutines = "1.7.1" 7 | 8 | [libraries] 9 | junit = "junit:junit:4.13.2" 10 | kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } 11 | kotlinx-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines"} 12 | kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } 13 | mobius-core = { module = "com.spotify.mobius:mobius-core", version.ref = "mobius" } 14 | mobius-test = { module = "com.spotify.mobius:mobius-test", version.ref = "mobius" } 15 | turbine = "app.cash.turbine:turbine:0.7.0" 16 | 17 | [plugins] 18 | kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } 19 | gradle-maven-publish-plugin = { id = "com.vanniktech.maven.publish", version = "0.25.2"} -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atlassian-labs/Flowbius/f99da6fd36fce37a766a00b7c29abe2393deb95b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':flowbius' 2 | --------------------------------------------------------------------------------