├── .editorconfig
├── .github
├── CODEOWNERS
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── Bug_report.md
│ └── Feature_request.md
├── pull_request_template.md
└── workflows
│ ├── android.yml
│ └── publish.yml
├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle.kts
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── kotlin
│ └── com
│ │ └── skydoves
│ │ └── flow
│ │ └── operators
│ │ └── demo
│ │ ├── MainActivity.kt
│ │ ├── MainViewModel.kt
│ │ ├── MainViewModelFactory.kt
│ │ ├── data
│ │ └── MainRepository.kt
│ │ └── network
│ │ ├── DisneyService.kt
│ │ ├── NetworkModule.kt
│ │ └── Poster.kt
│ └── res
│ ├── drawable
│ ├── ic_launcher_background.xml
│ └── ic_launcher_foreground.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-mdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── values
│ ├── colors.xml
│ ├── strings.xml
│ └── themes.xml
│ └── xml
│ ├── backup_rules.xml
│ └── data_extraction_rules.xml
├── build.gradle.kts
├── buildSrc
├── build.gradle.kts
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── skydoves
│ └── flow
│ └── operators
│ └── Configuration.kt
├── flow-operators
├── .gitignore
├── api
│ ├── android
│ │ └── flow-operators.api
│ └── jvm
│ │ └── flow-operators.api
├── build.gradle.kts
└── src
│ ├── commonMain
│ └── kotlin
│ │ └── com
│ │ └── skydoves
│ │ └── flow
│ │ └── operators
│ │ ├── onetime
│ │ └── OnetimeStateIn.kt
│ │ ├── pausable
│ │ ├── Pausable.kt
│ │ ├── PausableStateFlow.kt
│ │ └── PausableStateIn.kt
│ │ └── restartable
│ │ ├── Restartable.kt
│ │ ├── RestartableStateFlow.kt
│ │ └── RestartableStateIn.kt
│ └── commonTest
│ └── kotlin
│ └── com
│ └── skydoves
│ └── flow
│ └── operators
│ ├── OnetimeWhileSubscribedTest.kt
│ ├── PausableTest.kt
│ └── RestartableTest.kt
├── gradle.properties
├── gradle
├── libs.versions.toml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── scripts
└── publish-module.gradle.kts
├── settings.gradle.kts
└── spotless
├── copyright.kt
├── copyright.kts
└── copyright.xml
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 | [*]
3 | # Most of the standard properties are supported
4 | indent_size=2
5 | max_line_length=100
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # Lines starting with '#' are comments.
2 | # Each line is a file pattern followed by one or more owners.
3 |
4 | # More details are here: https://help.github.com/articles/about-codeowners/
5 |
6 | # The '*' pattern is global owners.
7 | # Not adding in this PR, but I'd like to try adding a global owner set with the entire team.
8 | # One interpretation of their docs is that global owners are added only if not removed
9 | # by a more local rule.
10 |
11 | # Order is important. The last matching pattern has the most precedence.
12 | # The folders are ordered as follows:
13 |
14 | # In each subsection folders are ordered first by depth, then alphabetically.
15 | # This should make it easy to add new rules without breaking existing ones.
16 | * @skydoves
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: skydoves
2 | custom: ["https://www.paypal.me/skydoves", "https://www.buymeacoffee.com/skydoves"]
3 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Something is crashing or not working as intended
4 |
5 | ---
6 |
7 | **Please complete the following information:**
8 | - Library Version [e.g. v1.0.0]
9 | - Affected Device(s) [e.g. Samsung Galaxy s10 with Android 9.0]
10 |
11 | **Describe the Bug:**
12 |
13 | Add a clear description about the problem.
14 |
15 | **Expected Behavior:**
16 |
17 | A clear description of what you expected to happen.
18 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/Feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 |
5 | ---
6 |
7 | **Is your feature request related to a problem?**
8 |
9 | A clear and concise description of what the problem is.
10 |
11 | **Describe the solution you'd like:**
12 |
13 | A clear and concise description of what you want to happen.
14 |
15 | **Describe alternatives you've considered:**
16 |
17 | A clear description of any alternative solutions you've considered.
18 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ### 🎯 Goal
2 | Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue.
3 |
4 | ### 🛠 Implementation details
5 | Describe the implementation details for this Pull Request.
6 |
7 | ### ✍️ Explain examples
8 | Explain examples with code for these updates.
9 |
10 | ### Preparing a pull request for review
11 | Ensure your change is properly formatted by running:
12 |
13 | ```bash
14 | $ ./gradlew spotlessApply
15 | ```
16 |
17 | Then dump binary APIs of this library that is public in sense of Kotlin visibilities and ensures that the public binary API wasn't changed in a way that makes this change binary incompatible.
18 |
19 | ```bash
20 | ./gradlew apiDump
21 | ```
22 |
23 | Please correct any failures before requesting a review.
24 |
25 | ## Code reviews
26 | All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests) for more information on using pull requests.
27 |
--------------------------------------------------------------------------------
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | jobs:
10 | lint:
11 | name: Spotless check
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Check out code
15 | uses: actions/checkout@v4.1.7
16 | - name: Set up JDK
17 | uses: actions/setup-java@v4.2.2
18 | with:
19 | distribution: zulu
20 | java-version: 17
21 | - uses: gradle/gradle-build-action@v3.5.0
22 | - name: spotless
23 | run: ./gradlew spotlessCheck
24 |
25 | api_check:
26 | name: API check
27 | runs-on: ubuntu-latest
28 | steps:
29 | - name: Check out code
30 | uses: actions/checkout@v4.1.7
31 | - name: Set up JDK
32 | uses: actions/setup-java@v4.2.2
33 | with:
34 | distribution: zulu
35 | java-version: 17
36 | - uses: gradle/gradle-build-action@v3.5.0
37 | - name: API check
38 | run: ./gradlew apiCheck
39 |
40 | build:
41 | runs-on: ubuntu-latest
42 | steps:
43 | - uses: actions/checkout@v4.1.7
44 | - name: set up JDK
45 | uses: actions/setup-java@v4.2.2
46 | with:
47 | distribution: zulu
48 | java-version: 17
49 |
50 | - uses: gradle/gradle-build-action@v3.5.0
51 | - name: Make Gradle executable
52 | run: chmod +x ./gradlew
53 |
54 | - name: Build with Gradle
55 | run: |
56 | ./gradlew --scan --stacktrace \
57 | assemble
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish
2 |
3 | on:
4 | release:
5 | types: [ released ]
6 | workflow_dispatch:
7 |
8 | jobs:
9 | publish:
10 | name: Snapshot build and publish
11 | runs-on: macos-latest
12 | steps:
13 | - name: Check out code
14 | uses: actions/checkout@v4.1.7
15 |
16 | - name: Set up JDK 17
17 | uses: actions/setup-java@v4.2.2
18 | with:
19 | distribution: 'zulu'
20 | java-version: 17
21 |
22 | - name: Grant Permission to Execute Gradle
23 | run: chmod +x gradlew
24 |
25 | - name: Release build
26 | run: ./gradlew assemble --scan
27 |
28 | - name: Publish to MavenCentral
29 | run: |
30 | ./gradlew publishAllPublicationsToMavenCentral --no-configuration-cache
31 | env:
32 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.OSSRH_USERNAME }}
33 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.OSSRH_PASSWORD }}
34 | ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }}
35 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
36 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_KEY }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | /.idea
18 | !.idea/codeInsightSettings.xml
19 | .gradle/
20 | build/
21 |
22 | # Local configuration file (sdk path, etc)
23 | local.properties
24 | secrets.properties
25 |
26 | # Proguard folder generated by Eclipse
27 | proguard/
28 |
29 | # Log Files
30 | *.log
31 |
32 | # Android Studio Navigation editor temp files
33 | .navigation/
34 |
35 | # Android Studio captures folder
36 | captures/
37 |
38 | # Intellij
39 | *.iml
40 | .idea/workspace.xml
41 | .idea/tasks.xml
42 | .idea/gradle.xml
43 | .idea/dictionaries
44 | .idea/libraries
45 | app/.idea/
46 |
47 | # Mac
48 | *.DS_Store
49 |
50 | # Keystore files
51 | *.jks
52 |
53 | # External native build folder generated in Android Studio 2.2 and later
54 | .externalNativeBuild
55 |
56 | # Google Services (e.g. APIs or Firebase)
57 | google-services.json
58 |
59 | # Freeline
60 | freeline.py
61 | freeline/
62 | freeline_project_description.json
63 |
64 | # Eclipse
65 | .project
66 | .settings
67 | .classpath
68 |
69 | # Kotlin
70 | .kotlin
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Flow Operators
2 |
3 |
4 |
5 |
6 |
8 |
9 |
10 |
11 |
12 | 🌊 Flow operators enable you to create restartable, pausable, or one-shot StateFlow, and they support KMP.
13 |
14 | ## Flow Operators
15 |
16 | Flow operators that enable you to create restartable, pausable, or one-shot `StateFlow` instances, allowing you to customize and control additional behaviors for `StateFlow` based on your specific use case. Why are flow operators useful? You can manage state and control data streams efficiently in complex scenarios. You can read more about the reasons in [Loading Initial Data on Android Part 2: Clear All Your Doubts](https://medium.com/proandroiddev/loading-initial-data-part-2-clear-all-your-doubts-0f621bfd06a0).
17 |
18 | [](https://search.maven.org/search?q=g:%22com.github.skydoves%22%20AND%20a:%22flow-operators%22)
19 |
20 | ### Version Catalog
21 |
22 | If you're using Version Catalog, you can configure the dependency by adding it to your `libs.versions.toml` file as follows:
23 |
24 | ```toml
25 | [versions]
26 | #...
27 | flowOperators = "0.1.1"
28 |
29 | [libraries]
30 | #...
31 | flow-operators = { module = "com.github.skydoves:flow-operators", version.ref = "flowOperators" }
32 | ```
33 |
34 | ### Gradle
35 | Add the dependency below to your **module**'s `build.gradle.kts` file:
36 |
37 | ```gradle
38 | dependencies {
39 | implementation("com.github.skydoves:flow-operators:$version")
40 |
41 | // if you're using Version Catalog
42 | implementation(libs.flow.operators)
43 | }
44 | ```
45 |
46 | For Kotlin Multiplatform, add the dependency below to your **module**'s `build.gradle.kts` file:
47 |
48 | ```gradle
49 | sourceSets {
50 | val commonMain by getting {
51 | dependencies {
52 | implementation("com.github.skydoves:flow-operators:$version")
53 | }
54 | }
55 | }
56 | ```
57 |
58 | ### RestartableStateFlow
59 |
60 | `RestartableStateFlow` extends both `StateFlow` and `Restartable`, allowing the upstream flow to restart its emission. It behaves like a regular `StateFlow` but includes the ability to reset and restart the emission process when necessary.
61 |
62 | Consider a scenario where you load initial data using a property, as shown in the example below, instead of initiating the load inside `LaunchedEffect` or `ViewModel.init()`. (For more details, check out [Loading Initial Data in LaunchedEffect vs. ViewModel](https://medium.com/proandroiddev/loading-initial-data-in-launchedeffect-vs-viewmodel-f1747c20ce62)).
63 |
64 | ```kotlin
65 | val posters: StateFlow> = mainRepository.fetchPostersFlow()
66 | .filter { it.isSuccess }
67 | .mapLatest { it.getOrThrow() }
68 | .restartableStateIn(
69 | scope = viewModelScope,
70 | started = SharingStarted.WhileSubscribed(5000),
71 | initialValue = emptyList(),
72 | )
73 | ```
74 |
75 | By using a property, the data is loaded only when the first subscription occurs, preventing the unnecessary immediate execution of tasks and avoiding unintended side effects that might arise from `ViewModel.init()` or `LaunchedEffect`. However, another challenge arises: you may need to reload the data due to scenarios like refreshing, recovering from errors during the initial load, or other reasons. In such cases, you can seamlessly restart the upstream flow using `RestartableStateFlow`.
76 |
77 | ```kotlin
78 | class MainViewModel(mainRepository: MainRepository) : ViewModel() {
79 |
80 | private val restartablePoster: RestartableStateFlow> = mainRepository.fetchPostersFlow()
81 | .filter { it.isSuccess }
82 | .mapLatest { it.getOrThrow() }
83 | .restartableStateIn(
84 | scope = viewModelScope,
85 | started = SharingStarted.WhileSubscribed(5000),
86 | initialValue = emptyList(),
87 | )
88 |
89 | val posters: StateFlow> = restartablePoster // don't expose the Restartable interface to the outside
90 |
91 | fun refresh() = restartablePoster.restart()
92 | }
93 | ```
94 |
95 | Now, you can easily restart the upstream flow and reload the initial task using the property.
96 |
97 | ```kotlin
98 | @Composable
99 | private fun Main(mainViewModel: MainViewModel) {
100 | val posters by mainViewModel.posters.collectAsStateWithLifecycle()
101 |
102 | Column(
103 | modifier = Modifier
104 | .fillMaxSize()
105 | .padding(6.dp)
106 | .verticalScroll(rememberScrollState()),
107 | ) {
108 | Button(onClick = { mainViewModel.refresh() }) {
109 | Text(text = "restart")
110 | }
111 |
112 | Text(text = posters.toString())
113 | }
114 | }
115 | ```
116 |
117 | ### PausableStateFlow
118 |
119 | `PausableStateFlow` extends both `StateFlow` and `PausableStateFlow`, enabling the upstream flow to pause and resume its emission. It retains the functionality of a standard `StateFlow` while adding controls for pausing and resuming emissions as needed.
120 |
121 | The core concept of `PausableStateFlow` is similar to `RestartableStateFlow`, but with an added capability: it allows you to pause and resume listening to the upstream flow. This can be particularly useful in scenarios where you want to temporarily stop processing updates from an upstream flow, such as real-time location updates, Bluetooth connection status, animations, or other continuous events.
122 |
123 | While paused, any new subscribers to the `PausableStateFlow` will simply receive the latest cached value instead of actively listening to the upstream emissions.
124 |
125 | ```kotlin
126 | class MainViewModel(mainRepository: MainRepository) : ViewModel() {
127 |
128 | private val pausableStateFlow: PausableStateFlow> =
129 | mainRepository.fetchPostersFlow()
130 | .filter { it.isSuccess }
131 | .mapLatest { it.getOrThrow() }
132 | .pausableStateIn(
133 | scope = viewModelScope,
134 | started = SharingStarted.WhileSubscribed(5000),
135 | initialValue = emptyList(),
136 | )
137 |
138 | val posters: StateFlow> = pausableStateFlow
139 |
140 | fun pause() = pausableStateFlow.pause()
141 |
142 | fun resume() = pausableStateFlow.resume()
143 | }
144 | ```
145 |
146 | ### OnetimeWhileSubscribed
147 |
148 | `OnetimeWhileSubscribed` is a `SharingStarted` strategy that ensures the upstream flow emits only once while a subscriber is active. After the initial emission, it remains idle until another active subscription appears.
149 |
150 | When converting a cold flow into a hot flow using `stateIn` on Android, a common approach is to use `SharingStarted.WhileSubscribed(5_000)` with the `stateIn` function. The 5-second threshold (5_000) aligns with the ANR (Application Not Responding) timeout limit. If no subscribers remain for longer than 5 seconds, the timeout is exceeded, and the upstream data flow ceases to influence your UI layer.
151 |
152 | However, this can lead to another side-effect: if you navigate from Screen A to Screen B and remain on Screen B for over 5 seconds, returning to Screen A will restart the upstream flow. This causes the same task to relaunch, even if it was already completed. To avoid this, you can use `OnetimeWhileSubscribed` as a `SharingStarted` strategy. It ensures the upstream flow is launched only once when the first subscription occurs, and subsequently, only the latest cached value is replayed, avoiding redundant task restarts during screen transitions.
153 |
154 | ```kotlin
155 | class MainViewModel(mainRepository: MainRepository) : ViewModel() {
156 |
157 | private val posters: StateFlow> =
158 | mainRepository.fetchPostersFlow()
159 | .filter { it.isSuccess }
160 | .mapLatest { it.getOrThrow() }
161 | .stateIn(
162 | scope = viewModelScope,
163 | started = SharingStarted.OnetimeWhileSubscribed(5_000),
164 | initialValue = emptyList(),
165 | )
166 | }
167 | ```
168 |
169 | ## Find this repository useful? :heart:
170 | Support it by joining __[stargazers](https://github.com/skydoves/flow-operators/stargazers)__ for this repository. :star:
171 | Also, __[follow me](https://github.com/skydoves)__ on GitHub for my next creations! 🤩
172 |
173 | # License
174 | ```xml
175 | Designed and developed by 2025 skydoves (Jaewoong Eum)
176 |
177 | Licensed under the Apache License, Version 2.0 (the "License");
178 | you may not use this file except in compliance with the License.
179 | You may obtain a copy of the License at
180 |
181 | http://www.apache.org/licenses/LICENSE-2.0
182 |
183 | Unless required by applicable law or agreed to in writing, software
184 | distributed under the License is distributed on an "AS IS" BASIS,
185 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
186 | See the License for the specific language governing permissions and
187 | limitations under the License.
188 | ```
189 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | import com.skydoves.flow.operators.Configuration
17 |
18 | plugins {
19 | id(libs.plugins.android.application.get().pluginId)
20 | id(libs.plugins.kotlin.android.get().pluginId)
21 | id(libs.plugins.compose.compiler.get().pluginId)
22 | id(libs.plugins.kotlin.serialization.get().pluginId)
23 | id(libs.plugins.ksp.get().pluginId)
24 | }
25 |
26 | android {
27 | compileSdk = Configuration.compileSdk
28 | namespace = "com.skydoves.flow.operators.demo"
29 | defaultConfig {
30 | applicationId = "com.skydoves.flow.operators.demo"
31 | minSdk = Configuration.minSdk
32 | targetSdk = Configuration.targetSdk
33 | versionCode = Configuration.versionCode
34 | versionName = Configuration.versionName
35 | }
36 |
37 | buildFeatures {
38 | compose = true
39 | }
40 |
41 | lint {
42 | abortOnError = false
43 | }
44 |
45 | compileOptions {
46 | sourceCompatibility = JavaVersion.VERSION_17
47 | targetCompatibility = JavaVersion.VERSION_17
48 | }
49 |
50 | kotlinOptions {
51 | jvmTarget = "17"
52 | }
53 | }
54 |
55 | dependencies {
56 | implementation(project(":flow-operators"))
57 |
58 | implementation(libs.androidx.activity.compose)
59 | implementation(libs.androidx.compose.ui)
60 | implementation(libs.androidx.compose.material3)
61 | implementation(libs.androidx.compose.foundation)
62 | implementation(libs.androidx.compose.runtime)
63 | implementation(libs.androidx.compose.ui.tooling.preview)
64 | implementation(libs.androidx.lifecycle.runtime)
65 | implementation(libs.androidx.lifecycle.runtimeCompose)
66 | implementation(libs.androidx.lifecycle.viewModelCompose)
67 |
68 | implementation(libs.kotlinx.serialization.json)
69 |
70 | implementation(libs.sandwich)
71 | implementation(libs.kotlinx.coroutines.core)
72 | implementation(libs.retrofit)
73 | implementation(libs.retrofit.kotlinx.serialization)
74 | }
75 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
17 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo
17 |
18 | import android.os.Bundle
19 | import androidx.activity.ComponentActivity
20 | import androidx.activity.compose.setContent
21 | import androidx.compose.foundation.layout.Column
22 | import androidx.compose.foundation.layout.fillMaxSize
23 | import androidx.compose.foundation.layout.padding
24 | import androidx.compose.foundation.rememberScrollState
25 | import androidx.compose.foundation.verticalScroll
26 | import androidx.compose.material3.Button
27 | import androidx.compose.material3.MaterialTheme
28 | import androidx.compose.material3.Text
29 | import androidx.compose.runtime.Composable
30 | import androidx.compose.runtime.getValue
31 | import androidx.compose.ui.Modifier
32 | import androidx.compose.ui.unit.dp
33 | import androidx.lifecycle.compose.collectAsStateWithLifecycle
34 |
35 | class MainActivity : ComponentActivity() {
36 |
37 | private val viewModelFactory: MainViewModelFactory = MainViewModelFactory()
38 | private val viewModel: MainViewModel by lazy {
39 | viewModelFactory.create(MainViewModel::class.java)
40 | }
41 |
42 | override fun onCreate(savedInstanceState: Bundle?) {
43 | super.onCreate(savedInstanceState)
44 |
45 | setContent {
46 | MaterialTheme {
47 | Main(mainViewModel = viewModel)
48 | }
49 | }
50 | }
51 | }
52 |
53 | @Composable
54 | private fun Main(mainViewModel: MainViewModel) {
55 | val posters by mainViewModel.posters.collectAsStateWithLifecycle()
56 |
57 | Column(
58 | modifier = Modifier
59 | .fillMaxSize()
60 | .padding(6.dp)
61 | .verticalScroll(rememberScrollState()),
62 | ) {
63 | Button(onClick = { mainViewModel.restart() }) {
64 | Text(text = "restart")
65 | }
66 |
67 | Text(text = posters.toString())
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo
17 |
18 | import androidx.lifecycle.ViewModel
19 | import androidx.lifecycle.viewModelScope
20 | import com.skydoves.flow.operators.demo.data.MainRepository
21 | import com.skydoves.flow.operators.demo.network.Poster
22 | import com.skydoves.flow.operators.restartable.RestartableStateFlow
23 | import com.skydoves.flow.operators.restartable.restartableStateIn
24 | import com.skydoves.sandwich.getOrThrow
25 | import com.skydoves.sandwich.isSuccess
26 | import kotlinx.coroutines.ExperimentalCoroutinesApi
27 | import kotlinx.coroutines.flow.SharingStarted
28 | import kotlinx.coroutines.flow.StateFlow
29 | import kotlinx.coroutines.flow.filter
30 | import kotlinx.coroutines.flow.mapLatest
31 |
32 | class MainViewModel(mainRepository: MainRepository) : ViewModel() {
33 |
34 | @OptIn(ExperimentalCoroutinesApi::class)
35 | private val restartablePoster: RestartableStateFlow> =
36 | mainRepository.fetchPostersFlow()
37 | .filter { it.isSuccess }
38 | .mapLatest { it.getOrThrow() }
39 | .restartableStateIn(
40 | scope = viewModelScope,
41 | started = SharingStarted.WhileSubscribed(5000),
42 | initialValue = emptyList(),
43 | )
44 |
45 | val posters: StateFlow> = restartablePoster
46 |
47 | fun restart() {
48 | restartablePoster.restart()
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/MainViewModelFactory.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo
17 |
18 | import androidx.lifecycle.ViewModel
19 | import androidx.lifecycle.ViewModelProvider
20 | import com.skydoves.flow.operators.demo.data.MainRepository
21 | import com.skydoves.flow.operators.demo.network.NetworkModule
22 |
23 | @Suppress("UNCHECKED_CAST")
24 | class MainViewModelFactory : ViewModelProvider.Factory {
25 |
26 | override fun create(modelClass: Class): T {
27 | if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
28 | val mainRepository = MainRepository(NetworkModule.disneyService)
29 | return MainViewModel(mainRepository) as T
30 | }
31 | throw IllegalArgumentException("Unknown ViewModel class.")
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/data/MainRepository.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo.data
17 |
18 | import android.util.Log
19 | import com.skydoves.flow.operators.demo.network.DisneyService
20 | import com.skydoves.flow.operators.demo.network.Poster
21 | import com.skydoves.sandwich.ApiResponse
22 | import kotlinx.coroutines.flow.Flow
23 | import kotlinx.coroutines.flow.flow
24 |
25 | class MainRepository(private val disneyService: DisneyService) {
26 |
27 | fun fetchPostersFlow(): Flow>> = flow {
28 | Log.d("MainRepository", "fetchPostersFlow")
29 | val response = disneyService.fetchDisneyPosters()
30 | emit(response)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/network/DisneyService.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo.network
17 |
18 | import com.skydoves.sandwich.ApiResponse
19 | import retrofit2.http.GET
20 |
21 | interface DisneyService {
22 |
23 | @GET("DisneyPosters.json")
24 | suspend fun fetchDisneyPosters(): ApiResponse>
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/network/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo.network
17 |
18 | import com.skydoves.sandwich.retrofit.adapters.ApiResponseCallAdapterFactory
19 | import kotlinx.serialization.json.Json
20 | import okhttp3.MediaType.Companion.toMediaType
21 | import okhttp3.OkHttpClient
22 | import retrofit2.Retrofit
23 | import retrofit2.converter.kotlinx.serialization.asConverterFactory
24 |
25 | object NetworkModule {
26 |
27 | private val okHttpClient: OkHttpClient =
28 | OkHttpClient.Builder().build()
29 |
30 | private val retrofit: Retrofit = Retrofit.Builder()
31 | .client(okHttpClient)
32 | .baseUrl(
33 | "https://gist.githubusercontent.com/skydoves/aa3bbbf495b0fa91db8a9e89f34e4873/" +
34 | "raw/a1a13d37027e8920412da5f00f6a89c5a3dbfb9a/",
35 | )
36 | .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
37 | .addCallAdapterFactory(ApiResponseCallAdapterFactory.create())
38 | .build()
39 |
40 | val disneyService: DisneyService = retrofit.create(DisneyService::class.java)
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/skydoves/flow/operators/demo/network/Poster.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.demo.network
17 |
18 | import kotlinx.serialization.SerialName
19 | import kotlinx.serialization.Serializable
20 |
21 | @Serializable
22 | data class Poster(
23 | @SerialName("id") val id: Long,
24 | @SerialName("name") val name: String,
25 | @SerialName("release") val release: String,
26 | @SerialName("playtime") val playtime: String,
27 | @SerialName("description") val description: String,
28 | @SerialName("plot") val plot: String,
29 | @SerialName("poster") val poster: String,
30 | )
31 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | flow-operators
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | @Suppress("DSL_SCOPE_VIOLATION")
2 | plugins {
3 | alias(libs.plugins.android.application) apply false
4 | alias(libs.plugins.android.library) apply false
5 | alias(libs.plugins.kotlin.android) apply false
6 | alias(libs.plugins.compose.compiler) apply false
7 | alias(libs.plugins.kotlin.serialization) apply false
8 | alias(libs.plugins.kotlin.multiplatform) apply false
9 | alias(libs.plugins.ksp) apply false
10 | alias(libs.plugins.kotlin.binary.compatibility)
11 | alias(libs.plugins.nexus.plugin)
12 | alias(libs.plugins.spotless)
13 | alias(libs.plugins.dokka)
14 | }
15 |
16 | apiValidation {
17 | ignoredProjects.addAll(listOf("app"))
18 | }
19 |
20 | subprojects {
21 | apply(plugin = rootProject.libs.plugins.spotless.get().pluginId)
22 | configure {
23 | kotlin {
24 | target("**/*.kt")
25 | targetExclude("$buildDir/**/*.kt")
26 | ktlint().editorConfigOverride(
27 | mapOf(
28 | "indent_size" to "2",
29 | "continuation_indent_size" to "2"
30 | )
31 | )
32 | licenseHeaderFile(rootProject.file("spotless/copyright.kt"))
33 | trimTrailingWhitespace()
34 | endWithNewline()
35 | }
36 | format("kts") {
37 | target("**/*.kts")
38 | targetExclude("$buildDir/**/*.kts")
39 | licenseHeaderFile(rootProject.file("spotless/copyright.kt"), "(^(?![\\/ ]\\*).*$)")
40 | trimTrailingWhitespace()
41 | endWithNewline()
42 | }
43 | }
44 | }
--------------------------------------------------------------------------------
/buildSrc/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | `kotlin-dsl`
3 | }
4 |
5 | repositories {
6 | mavenCentral()
7 | }
--------------------------------------------------------------------------------
/buildSrc/src/main/kotlin/com/skydoves/flow/operators/Configuration.kt:
--------------------------------------------------------------------------------
1 | package com.skydoves.flow.operators
2 |
3 | object Configuration {
4 | const val compileSdk = 35
5 | const val targetSdk = 35
6 | const val minSdk = 21
7 | const val majorVersion = 0
8 | const val minorVersion = 1
9 | const val patchVersion = 1
10 | const val versionName = "$majorVersion.$minorVersion.$patchVersion"
11 | const val versionCode = 2
12 | const val snapshotVersionName = "$majorVersion.$minorVersion.${patchVersion + 1}-SNAPSHOT"
13 | const val artifactGroup = "com.github.skydoves"
14 | }
15 |
--------------------------------------------------------------------------------
/flow-operators/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/flow-operators/api/android/flow-operators.api:
--------------------------------------------------------------------------------
1 | public final class com/skydoves/flow/operators/onetime/OnetimeStateInKt {
2 | public static final fun OnetimeWhileSubscribed (Lkotlinx/coroutines/flow/SharingStarted$Companion;JJ)Lkotlinx/coroutines/flow/SharingStarted;
3 | public static synthetic fun OnetimeWhileSubscribed$default (Lkotlinx/coroutines/flow/SharingStarted$Companion;JJILjava/lang/Object;)Lkotlinx/coroutines/flow/SharingStarted;
4 | public static final fun onetimeStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;JJLjava/lang/Object;)Lkotlinx/coroutines/flow/StateFlow;
5 | public static synthetic fun onetimeStateIn$default (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;JJLjava/lang/Object;ILjava/lang/Object;)Lkotlinx/coroutines/flow/StateFlow;
6 | }
7 |
8 | public abstract interface class com/skydoves/flow/operators/pausable/Pausable {
9 | public abstract fun pause ()V
10 | public abstract fun resume ()V
11 | }
12 |
13 | public abstract interface class com/skydoves/flow/operators/pausable/PausableStateFlow : com/skydoves/flow/operators/pausable/Pausable, kotlinx/coroutines/flow/StateFlow {
14 | public abstract fun pause ()V
15 | public abstract fun resume ()V
16 | }
17 |
18 | public final class com/skydoves/flow/operators/pausable/PausableStateInKt {
19 | public static final fun pausableStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;Lkotlinx/coroutines/flow/SharingStarted;Ljava/lang/Object;)Lcom/skydoves/flow/operators/pausable/PausableStateFlow;
20 | }
21 |
22 | public abstract interface class com/skydoves/flow/operators/restartable/Restartable {
23 | public abstract fun restart ()V
24 | }
25 |
26 | public abstract interface class com/skydoves/flow/operators/restartable/RestartableStateFlow : com/skydoves/flow/operators/restartable/Restartable, kotlinx/coroutines/flow/StateFlow {
27 | public abstract fun restart ()V
28 | }
29 |
30 | public final class com/skydoves/flow/operators/restartable/RestartableStateInKt {
31 | public static final fun restartableStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;Lkotlinx/coroutines/flow/SharingStarted;Ljava/lang/Object;)Lcom/skydoves/flow/operators/restartable/RestartableStateFlow;
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/flow-operators/api/jvm/flow-operators.api:
--------------------------------------------------------------------------------
1 | public final class com/skydoves/flow/operators/onetime/OnetimeStateInKt {
2 | public static final fun OnetimeWhileSubscribed (Lkotlinx/coroutines/flow/SharingStarted$Companion;JJ)Lkotlinx/coroutines/flow/SharingStarted;
3 | public static synthetic fun OnetimeWhileSubscribed$default (Lkotlinx/coroutines/flow/SharingStarted$Companion;JJILjava/lang/Object;)Lkotlinx/coroutines/flow/SharingStarted;
4 | public static final fun onetimeStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;JJLjava/lang/Object;)Lkotlinx/coroutines/flow/StateFlow;
5 | public static synthetic fun onetimeStateIn$default (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;JJLjava/lang/Object;ILjava/lang/Object;)Lkotlinx/coroutines/flow/StateFlow;
6 | }
7 |
8 | public abstract interface class com/skydoves/flow/operators/pausable/Pausable {
9 | public abstract fun pause ()V
10 | public abstract fun resume ()V
11 | }
12 |
13 | public abstract interface class com/skydoves/flow/operators/pausable/PausableStateFlow : com/skydoves/flow/operators/pausable/Pausable, kotlinx/coroutines/flow/StateFlow {
14 | public abstract fun pause ()V
15 | public abstract fun resume ()V
16 | }
17 |
18 | public final class com/skydoves/flow/operators/pausable/PausableStateInKt {
19 | public static final fun pausableStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;Lkotlinx/coroutines/flow/SharingStarted;Ljava/lang/Object;)Lcom/skydoves/flow/operators/pausable/PausableStateFlow;
20 | }
21 |
22 | public abstract interface class com/skydoves/flow/operators/restartable/Restartable {
23 | public abstract fun restart ()V
24 | }
25 |
26 | public abstract interface class com/skydoves/flow/operators/restartable/RestartableStateFlow : com/skydoves/flow/operators/restartable/Restartable, kotlinx/coroutines/flow/StateFlow {
27 | public abstract fun restart ()V
28 | }
29 |
30 | public final class com/skydoves/flow/operators/restartable/RestartableStateInKt {
31 | public static final fun restartableStateIn (Lkotlinx/coroutines/flow/Flow;Lkotlinx/coroutines/CoroutineScope;Lkotlinx/coroutines/flow/SharingStarted;Ljava/lang/Object;)Lcom/skydoves/flow/operators/restartable/RestartableStateFlow;
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/flow-operators/build.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | import com.skydoves.flow.operators.Configuration
17 |
18 | plugins {
19 | id(libs.plugins.android.library.get().pluginId)
20 | id(libs.plugins.kotlin.multiplatform.get().pluginId)
21 | id(libs.plugins.nexus.plugin.get().pluginId)
22 | }
23 |
24 | apply(from = "${rootDir}/scripts/publish-module.gradle.kts")
25 |
26 | mavenPublishing {
27 | val artifactId = "flow-operators"
28 | coordinates(
29 | Configuration.artifactGroup,
30 | artifactId,
31 | rootProject.extra.get("libVersion").toString()
32 | )
33 |
34 | pom {
35 | name.set(artifactId)
36 | description.set("Flow extensions enable you to create restartable, pausable, or one-shot StateFlow.")
37 | }
38 | }
39 |
40 | kotlin {
41 | listOf(
42 | iosX64(),
43 | iosArm64(),
44 | iosSimulatorArm64(),
45 | macosArm64(),
46 | macosX64(),
47 | ).forEach {
48 | it.binaries.framework {
49 | baseName = "common"
50 | }
51 | }
52 |
53 | androidTarget {
54 | publishLibraryVariants("release")
55 | }
56 |
57 | jvm {
58 | libs.versions.jvmTarget.get().toInt()
59 | compilations.all {
60 | kotlinOptions.jvmTarget = libs.versions.jvmTarget.get()
61 | }
62 | }
63 |
64 | applyDefaultHierarchyTemplate()
65 |
66 | sourceSets {
67 | all {
68 | languageSettings.optIn("kotlin.contracts.ExperimentalContracts")
69 | }
70 | val commonMain by getting {
71 | dependencies {
72 | implementation(libs.kotlinx.coroutines.core)
73 | }
74 | }
75 |
76 | val commonTest by getting {
77 | dependencies {
78 | implementation(libs.kotlinx.coroutines.test)
79 | implementation(libs.kotlinx.test)
80 | implementation(libs.turbine)
81 | }
82 | }
83 | }
84 |
85 | explicitApi()
86 | }
87 |
88 | android {
89 | compileSdk = Configuration.compileSdk
90 | namespace = "com.skydoves.flow.operators"
91 |
92 | defaultConfig {
93 | minSdk = Configuration.minSdk
94 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
95 | }
96 |
97 | compileOptions {
98 | sourceCompatibility = JavaVersion.VERSION_17
99 | targetCompatibility = JavaVersion.VERSION_17
100 | }
101 | }
102 |
103 | dependencies {
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/onetime/OnetimeStateIn.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | @file:OptIn(ExperimentalCoroutinesApi::class)
17 |
18 | package com.skydoves.flow.operators.onetime
19 |
20 | import kotlinx.coroutines.CoroutineScope
21 | import kotlinx.coroutines.ExperimentalCoroutinesApi
22 | import kotlinx.coroutines.delay
23 | import kotlinx.coroutines.flow.Flow
24 | import kotlinx.coroutines.flow.MutableStateFlow
25 | import kotlinx.coroutines.flow.SharingCommand
26 | import kotlinx.coroutines.flow.SharingStarted
27 | import kotlinx.coroutines.flow.StateFlow
28 | import kotlinx.coroutines.flow.combine
29 | import kotlinx.coroutines.flow.distinctUntilChanged
30 | import kotlinx.coroutines.flow.dropWhile
31 | import kotlinx.coroutines.flow.stateIn
32 | import kotlinx.coroutines.flow.transformLatest
33 |
34 | /**
35 | * Create an upstream cold flow as a StateFlow that triggers the upstream operation only once,
36 | * preventing re-execution no matter how many times it's subscribed.
37 | * After the initial emission, it will simply replay the latest cached value.
38 | *
39 | * @param scope the coroutine scope in which sharing is started.
40 | * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last
41 | * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately).
42 | * @param replayExpiration configures a delay (in milliseconds) between the stopping of
43 | * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the
44 | * [shareIn] operator and resets the cached value to the original `initialValue`
45 | * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever,
46 | * never reset buffer). Use zero value to expire the cache immediately.
47 | * @param initialValue the initial value of the state flow. This value is also used when the
48 | * state flow is reset using the [SharingStarted]. [WhileSubscribed] strategy with the
49 | * [replayExpiration] parameter.
50 | */
51 | public fun Flow.onetimeStateIn(
52 | scope: CoroutineScope,
53 | stopTimeout: Long,
54 | replayExpiration: Long = Long.MAX_VALUE,
55 | initialValue: T,
56 | ): StateFlow {
57 | return stateIn(
58 | scope = scope,
59 | started = SharingStarted.OnetimeWhileSubscribed(
60 | stopTimeout = stopTimeout,
61 | replayExpiration = replayExpiration,
62 | ),
63 | initialValue,
64 | )
65 | }
66 |
67 | /**
68 | * This is a companion extension of [SharingStarted], which is a [SharingStarted] strategy
69 | * designed to limit upstream emissions to only once. After the initial emission,
70 | * it remains inactive until an active subscriber reappears.
71 | *
72 | * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last
73 | * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately).
74 | * @param replayExpiration configures a delay (in milliseconds) between the stopping of
75 | * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the
76 | * [shareIn] operator and resets the cached value to the original `initialValue`
77 | * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever,
78 | * never reset buffer). Use zero value to expire the cache immediately.
79 | */
80 | public fun SharingStarted.Companion.OnetimeWhileSubscribed(
81 | stopTimeout: Long,
82 | replayExpiration: Long = Long.MAX_VALUE,
83 | ): SharingStarted {
84 | return OnetimeWhileSubscribedImpl(
85 | stopTimeout = stopTimeout,
86 | replayExpiration = replayExpiration,
87 | )
88 | }
89 |
90 | /**
91 | * `OnetimeWhileSubscribed` is a [SharingStarted] strategy designed to limit upstream emissions to
92 | * only once. After the initial emission, it remains inactive until an active subscriber reappears.
93 | *
94 | * @param stopTimeout configures a delay (in milliseconds) between the disappearance of the last
95 | * subscriber and the stopping of the sharing coroutine. It defaults to zero (stop immediately).
96 | * @param replayExpiration configures a delay (in milliseconds) between the stopping of
97 | * the sharing coroutine and the resetting of the replay cache (which makes the cache empty for the
98 | * [shareIn] operator and resets the cached value to the original `initialValue`
99 | * for the [stateIn] operator). It defaults to `Long.MAX_VALUE` (keep replay cache forever,
100 | * never reset buffer). Use zero value to expire the cache immediately.
101 | */
102 | internal class OnetimeWhileSubscribedImpl(
103 | private val stopTimeout: Long,
104 | private val replayExpiration: Long = Long.MAX_VALUE,
105 | ) : SharingStarted {
106 |
107 | private val hasCollected: MutableStateFlow = MutableStateFlow(false)
108 |
109 | init {
110 | require(stopTimeout >= 0) { "stopTimeout($stopTimeout ms) cannot be negative" }
111 | require(replayExpiration >= 0) { "replayExpiration($replayExpiration ms) cannot be negative" }
112 | }
113 |
114 | override fun command(subscriptionCount: StateFlow): Flow =
115 | combine(hasCollected, subscriptionCount) { collected, counts ->
116 | collected to counts
117 | }
118 | .transformLatest { pair ->
119 | val (collected, count) = pair
120 | if (count > 0 && !collected) {
121 | emit(SharingCommand.START)
122 | hasCollected.value = true
123 | } else {
124 | delay(stopTimeout)
125 | if (replayExpiration > 0) {
126 | emit(SharingCommand.STOP)
127 | delay(replayExpiration)
128 | }
129 | emit(SharingCommand.STOP_AND_RESET_REPLAY_CACHE)
130 | }
131 | }
132 | .dropWhile {
133 | it != SharingCommand.START
134 | } // don't emit any STOP/RESET_BUFFER to start with, only START
135 | .distinctUntilChanged() // just in case somebody forgets it, don't leak our multiple sending of START
136 |
137 | override fun toString(): String {
138 | val params = buildList(2) {
139 | if (stopTimeout > 0) add("stopTimeout=${stopTimeout}ms")
140 | if (replayExpiration < Long.MAX_VALUE) add("replayExpiration=${replayExpiration}ms")
141 | }
142 | return "OnetimeWhileSubscribed(${params.joinToString()})"
143 | }
144 |
145 | // equals & hashcode to facilitate testing, not documented in public contract
146 | override fun equals(other: Any?): Boolean =
147 | other is OnetimeWhileSubscribedImpl &&
148 | stopTimeout == other.stopTimeout &&
149 | replayExpiration == other.replayExpiration
150 |
151 | override fun hashCode(): Int = stopTimeout.hashCode() * 31 + replayExpiration.hashCode()
152 | }
153 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/pausable/Pausable.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.pausable
17 |
18 | /**
19 | * The restartable interface defines two action: [pause], and [resume].
20 | */
21 | public interface Pausable {
22 | /**
23 | * The representation of the [Pausable] object should be able to pause an action.
24 | */
25 | public fun pause()
26 |
27 | /**
28 | * The representation of the [Pausable] object should be able to resume an action.
29 | */
30 | public fun resume()
31 | }
32 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/pausable/PausableStateFlow.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.pausable
17 |
18 | import kotlinx.coroutines.flow.StateFlow
19 |
20 | /**
21 | * [PausableStateFlow] extends both [StateFlow] and [PausableStateFlow], and is designed to
22 | * pause and resume the emission of the upstream flow. It functions just like a regular [StateFlow],
23 | * but with the added ability to pause and resume the upstream emission when needed.
24 | */
25 | public interface PausableStateFlow : StateFlow, Pausable {
26 | /**
27 | * The representation of the [Pausable] object that should be able to pause an action.
28 | */
29 | override fun pause()
30 |
31 | /**
32 | * The representation of the [Pausable] object that should be able to resume an action.
33 | */
34 | override fun resume()
35 | }
36 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/pausable/PausableStateIn.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.pausable
17 |
18 | import kotlinx.coroutines.CoroutineScope
19 | import kotlinx.coroutines.flow.Flow
20 | import kotlinx.coroutines.flow.MutableSharedFlow
21 | import kotlinx.coroutines.flow.SharingCommand
22 | import kotlinx.coroutines.flow.SharingStarted
23 | import kotlinx.coroutines.flow.StateFlow
24 | import kotlinx.coroutines.flow.merge
25 | import kotlinx.coroutines.flow.stateIn
26 |
27 | /**
28 | * `pausableStateIn` returns [PausableStateFlow] that implements both [StateFlow] and
29 | * [Pausable], and is designed to pause and resume the emission of the upstream flow.
30 | * It functions just like a regular [StateFlow], but with the added ability to pause and resume
31 | * the upstream emission when needed.
32 | *
33 | * @param scope the coroutine scope in which sharing is started.
34 | * @param started the strategy that controls when sharing is started and stopped.
35 | * @param initialValue the initial value of the state flow. This value is also used when the state flow
36 | * is reset using the SharingStarted. WhileSubscribed strategy with the replayExpirationMillis par
37 | */
38 | public fun Flow.pausableStateIn(
39 | scope: CoroutineScope,
40 | started: SharingStarted,
41 | initialValue: T,
42 | ): PausableStateFlow {
43 | val sharingRestartable = SharingPausableImpl(started)
44 | val stateFlow = stateIn(scope, sharingRestartable, initialValue)
45 | return object : PausableStateFlow, StateFlow by stateFlow {
46 | override fun pause() = sharingRestartable.pause()
47 | override fun resume() = sharingRestartable.resume()
48 | }
49 | }
50 |
51 | /**
52 | * The internal implementation of the [SharingStarted] and [Pausable].
53 | */
54 | private data class SharingPausableImpl(
55 | private val sharingStarted: SharingStarted,
56 | ) : SharingStarted, Pausable {
57 |
58 | private val pausableFlow = MutableSharedFlow(extraBufferCapacity = 2)
59 |
60 | override fun command(subscriptionCount: StateFlow): Flow {
61 | return merge(pausableFlow, sharingStarted.command(subscriptionCount))
62 | }
63 |
64 | override fun pause() {
65 | pausableFlow.tryEmit(SharingCommand.STOP)
66 | }
67 |
68 | override fun resume() {
69 | pausableFlow.tryEmit(SharingCommand.START)
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/restartable/Restartable.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.restartable
17 |
18 | /**
19 | * The restartable interface defines one action: [restart].
20 | */
21 | public interface Restartable {
22 |
23 | /**
24 | * The representation of the [Restartable] object should be able to restart an action.
25 | */
26 | public fun restart()
27 | }
28 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/restartable/RestartableStateFlow.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.restartable
17 |
18 | import kotlinx.coroutines.flow.StateFlow
19 |
20 | /**
21 | * [RestartableStateFlow] extends both [StateFlow] and [Restartable], and is designed to restart
22 | * the emission of the upstream flow. It functions just like a regular [StateFlow], but with the
23 | * added ability to restart the upstream emission when needed.
24 | */
25 | public interface RestartableStateFlow : StateFlow, Restartable {
26 |
27 | /**
28 | * The representation of the [Restartable] object that should be able to restart an action.
29 | */
30 | override fun restart()
31 | }
32 |
--------------------------------------------------------------------------------
/flow-operators/src/commonMain/kotlin/com/skydoves/flow/operators/restartable/RestartableStateIn.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators.restartable
17 |
18 | import kotlinx.coroutines.CoroutineScope
19 | import kotlinx.coroutines.flow.Flow
20 | import kotlinx.coroutines.flow.MutableSharedFlow
21 | import kotlinx.coroutines.flow.SharingCommand
22 | import kotlinx.coroutines.flow.SharingStarted
23 | import kotlinx.coroutines.flow.StateFlow
24 | import kotlinx.coroutines.flow.merge
25 | import kotlinx.coroutines.flow.stateIn
26 |
27 | /**
28 | * `restartableStateIn` returns a [RestartableStateFlow] that implements both [StateFlow] and
29 | * [Restartable], and is designed to restart the emission of the upstream flow. It functions just
30 | * like a regular [StateFlow], but with the added ability to restart the upstream emission when needed.
31 | *
32 | * @param scope the coroutine scope in which sharing is started.
33 | * @param started the strategy that controls when sharing is started and stopped.
34 | * @param initialValue the initial value of the state flow. This value is also used when the state flow
35 | * is reset using the SharingStarted. WhileSubscribed strategy with the replayExpirationMillis par
36 | */
37 | public fun Flow.restartableStateIn(
38 | scope: CoroutineScope,
39 | started: SharingStarted,
40 | initialValue: T,
41 | ): RestartableStateFlow {
42 | val sharingRestartable = SharingRestartableImpl(started)
43 | val stateFlow = stateIn(scope, sharingRestartable, initialValue)
44 | return object : RestartableStateFlow, StateFlow by stateFlow {
45 | override fun restart() = sharingRestartable.restart()
46 | }
47 | }
48 |
49 | /**
50 | * The internal implementation of the [SharingStarted], and [Restartable].
51 | */
52 | private data class SharingRestartableImpl(
53 | private val sharingStarted: SharingStarted,
54 | ) : SharingStarted, Restartable {
55 |
56 | private val restartFlow = MutableSharedFlow(extraBufferCapacity = 2)
57 |
58 | override fun command(subscriptionCount: StateFlow): Flow {
59 | return merge(restartFlow, sharingStarted.command(subscriptionCount))
60 | }
61 |
62 | override fun restart() {
63 | restartFlow.tryEmit(SharingCommand.STOP_AND_RESET_REPLAY_CACHE)
64 | restartFlow.tryEmit(SharingCommand.START)
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/flow-operators/src/commonTest/kotlin/com/skydoves/flow/operators/OnetimeWhileSubscribedTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | @file:OptIn(ExperimentalCoroutinesApi::class)
17 |
18 | package com.skydoves.flow.operators
19 |
20 | import app.cash.turbine.test
21 | import com.skydoves.flow.operators.onetime.onetimeStateIn
22 | import kotlinx.coroutines.ExperimentalCoroutinesApi
23 | import kotlinx.coroutines.cancelChildren
24 | import kotlinx.coroutines.delay
25 | import kotlinx.coroutines.flow.MutableStateFlow
26 | import kotlinx.coroutines.flow.SharingStarted
27 | import kotlinx.coroutines.flow.first
28 | import kotlinx.coroutines.flow.flow
29 | import kotlinx.coroutines.flow.mapLatest
30 | import kotlinx.coroutines.flow.shareIn
31 | import kotlinx.coroutines.job
32 | import kotlinx.coroutines.test.runTest
33 | import kotlin.test.Test
34 | import kotlin.test.assertEquals
35 |
36 | class OnetimeWhileSubscribedTest {
37 |
38 | @Test
39 | fun `WhileSubscribed always emit values whenever collected`() = runTest {
40 | var executedCount = 0
41 |
42 | val stateFlow = flow {
43 | executedCount++
44 | emit(executedCount)
45 | }.shareIn(
46 | scope = backgroundScope,
47 | started = SharingStarted.WhileSubscribed(100),
48 | )
49 |
50 | assertEquals(0, executedCount)
51 | stateFlow.first()
52 | assertEquals(1, executedCount)
53 | delay(200)
54 | stateFlow.first()
55 | assertEquals(2, executedCount)
56 |
57 | coroutineContext.job.cancelChildren()
58 | }
59 |
60 | @Test
61 | fun `onetimeStateIn should emit a value only a single time`() = runTest {
62 | var executedCount = 0
63 |
64 | val mutableStateFlow = MutableStateFlow(0)
65 | val stateFlow = mutableStateFlow.mapLatest {
66 | ++executedCount
67 | executedCount.toString()
68 | }.onetimeStateIn(
69 | scope = backgroundScope,
70 | stopTimeout = 100,
71 | initialValue = "initial",
72 | )
73 |
74 | stateFlow.test {
75 | assertEquals(0, executedCount)
76 | assertEquals("initial", awaitItem())
77 |
78 | delay(200)
79 | mutableStateFlow.value = 1
80 |
81 | assertEquals(1, executedCount)
82 | assertEquals("1", awaitItem())
83 |
84 | delay(200)
85 | mutableStateFlow.value = 2
86 |
87 | delay(200)
88 | mutableStateFlow.value = 3
89 |
90 | expectNoEvents()
91 | }
92 |
93 | stateFlow.test {
94 | assertEquals(1, executedCount)
95 | assertEquals("1", awaitItem())
96 | expectNoEvents()
97 | }
98 |
99 | coroutineContext.job.cancelChildren()
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/flow-operators/src/commonTest/kotlin/com/skydoves/flow/operators/PausableTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators
17 |
18 | import app.cash.turbine.test
19 | import com.skydoves.flow.operators.pausable.PausableStateFlow
20 | import com.skydoves.flow.operators.pausable.pausableStateIn
21 | import kotlinx.coroutines.cancelChildren
22 | import kotlinx.coroutines.flow.SharingStarted
23 | import kotlinx.coroutines.flow.flow
24 | import kotlinx.coroutines.job
25 | import kotlinx.coroutines.test.runTest
26 | import kotlin.test.Test
27 | import kotlin.test.assertEquals
28 |
29 | class PausableTest {
30 |
31 | @Test
32 | fun `pausableFlow should paused and resumed the upstream cold flow`() = runTest {
33 | var restartCount = 0
34 |
35 | val restartableStateFlow: PausableStateFlow = flow {
36 | if (restartCount == 0) {
37 | emit("aaa")
38 | } else {
39 | emit("bbb")
40 | }
41 | restartCount++
42 | }.pausableStateIn(
43 | scope = backgroundScope,
44 | started = SharingStarted.Lazily,
45 | initialValue = "initial",
46 | )
47 |
48 | restartableStateFlow.test {
49 | assertEquals(0, restartCount)
50 | assertEquals("initial", awaitItem())
51 | assertEquals("aaa", awaitItem())
52 |
53 | restartableStateFlow.pause()
54 | restartableStateFlow.resume()
55 |
56 | assertEquals(1, restartCount)
57 | assertEquals("bbb", awaitItem())
58 |
59 | restartableStateFlow.pause()
60 |
61 | expectNoEvents()
62 | }
63 |
64 | coroutineContext.job.cancelChildren()
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/flow-operators/src/commonTest/kotlin/com/skydoves/flow/operators/RestartableTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 com.skydoves.flow.operators
17 |
18 | import app.cash.turbine.test
19 | import com.skydoves.flow.operators.restartable.RestartableStateFlow
20 | import com.skydoves.flow.operators.restartable.restartableStateIn
21 | import kotlinx.coroutines.cancelChildren
22 | import kotlinx.coroutines.flow.SharingStarted
23 | import kotlinx.coroutines.flow.flow
24 | import kotlinx.coroutines.job
25 | import kotlinx.coroutines.test.runTest
26 | import kotlin.test.Test
27 | import kotlin.test.assertEquals
28 |
29 | class RestartableTest {
30 |
31 | @Test
32 | fun `restartableFlow should should re-execute the upstream cold flow`() = runTest {
33 | var restartCount = 0
34 |
35 | val restartableStateFlow: RestartableStateFlow = flow {
36 | if (restartCount == 0) {
37 | emit("aaa")
38 | } else {
39 | emit("bbb")
40 | }
41 | restartCount++
42 | }.restartableStateIn(
43 | scope = backgroundScope,
44 | started = SharingStarted.Lazily,
45 | initialValue = "initial",
46 | )
47 |
48 | restartableStateFlow.test {
49 | assertEquals(0, restartCount)
50 | assertEquals("initial", awaitItem())
51 | assertEquals("aaa", awaitItem())
52 |
53 | restartableStateFlow.restart()
54 |
55 | assertEquals(1, restartCount)
56 | assertEquals("initial", awaitItem())
57 | assertEquals("bbb", awaitItem())
58 |
59 | restartableStateFlow.restart()
60 |
61 | cancelAndIgnoreRemainingEvents()
62 | }
63 |
64 | assertEquals(2, restartCount)
65 |
66 | coroutineContext.job.cancelChildren()
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # https://docs.gradle.org/current/userguide/build_environment.html#sec:configuring_jvm_memory
2 | org.gradle.jvmargs=-Xmx4g -XX:+HeapDumpOnOutOfMemoryError -XX:+UseParallelGC -Dlint.nullness.ignore-deprecated=true
3 |
4 | # https://docs.gradle.org/current/userguide/build_cache.html
5 | org.gradle.caching=true
6 |
7 | # When configured, Gradle will run in incubating parallel mode.
8 | # This option should only be used with decoupled projects. More details, visit
9 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
10 | org.gradle.parallel=true
11 |
12 | # Configure only necessary projects, useful with multimodule projects
13 | org.gradle.configureondemand=true
14 |
15 | # AndroidX Migration https://developer.android.com/jetpack/androidx/migrate
16 | android.useAndroidX=true
17 |
18 | # Removes uneccessary default build features
19 | android.defaults.buildfeatures.aidl=false
20 | android.defaults.buildfeatures.buildconfig=false
21 | android.defaults.buildfeatures.renderscript=false
22 | android.defaults.buildfeatures.resvalues=false
23 | android.defaults.buildfeatures.shaders=false
24 |
25 | # KMP
26 | kotlin.mpp.androidGradlePluginCompatibility.nowarn=true
27 |
28 | # Enables namespacing of each library's R class so that its R class includes only the
29 | # resources declared in the library itself and none from the library's dependencies,
30 | # thereby reducing the size of the R class for that library
31 | # https://developer.android.com/studio/releases/gradle-plugin#4.1-nontransitive-r-class
32 | android.nonTransitiveRClass=true
33 |
34 | ## Maven Central Publication ##
35 | systemProp.org.gradle.internal.publish.checksums.insecure=true
36 |
37 | # Increase timeout when pushing to Sonatype (otherwise we get timeouts)
38 | systemProp.org.gradle.internal.http.socketTimeout=120000
39 |
40 | POM_URL=https://github.com/skydoves/flow-operators/
41 | POM_SCM_URL=https://github.com/skydoves/flow-operators/
42 | POM_SCM_CONNECTION=scm:git:git://github.com/skydoves/flow-operators.git
43 | POM_SCM_DEV_CONNECTION=scm:git:git://github.com/skydoves/flow-operators.git
44 |
45 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
46 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
47 | POM_LICENCE_DIST=repo
48 |
49 | POM_DEVELOPER_ID=skydoves
50 | POM_DEVELOPER_NAME=Jaewoong Eum
51 | POM_DEVELOPER_URL=https://github.com/skydoves/
52 | POM_DEVELOPER_EMAIL=skydoves2@gmail.com
53 |
54 | SONATYPE_HOST=DEFAULT
55 | RELEASE_SIGNING_ENABLED=true
56 | SONATYPE_AUTOMATIC_RELEASE=true
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.6.1"
3 | jvmTarget = "17"
4 | androidxActivity = "1.10.0"
5 | androidxCompose = "1.7.6"
6 | androidxComposeMaterial3 = "1.3.1"
7 | androidxCore = "1.15.0"
8 | androidxProfileinstaller = "1.4.1"
9 | androidxLifecycle = "2.8.7"
10 | androidxTest = "1.6.2"
11 | hilt = "2.54"
12 | retrofit = "2.11.0"
13 | nexusPlugin = "0.29.0"
14 | dokka = "2.0.0"
15 | kotlin = "2.1.0"
16 | kotlinBinaryCompatibility = "0.17.0"
17 | kotlinxCoroutines = "1.10.1"
18 | kotlinxSerialization = "1.8.0"
19 | ksp = "2.1.0-1.0.29"
20 | okhttp = "4.12.0"
21 | landscapist = "2.4.6"
22 | sandwich = "2.0.10"
23 | spotless = "6.21.0"
24 | junit = "4.13.2"
25 | junitVersion = "1.2.1"
26 | espressoCore = "3.6.1"
27 | appcompat = "1.7.0"
28 | material = "1.12.0"
29 | turbine = "1.1.0"
30 |
31 | [libraries]
32 | landscapist-glide = { group = "com.github.skydoves", name = "landscapist-glide", version.ref = "landscapist" }
33 | landscapist-animation = { group = "com.github.skydoves", name = "landscapist-animation", version.ref = "landscapist" }
34 | landscapist-placeholder = { group = "com.github.skydoves", name = "landscapist-placeholder", version.ref = "landscapist" }
35 | androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "androidxActivity" }
36 | androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "androidxCompose" }
37 | androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "androidxCompose" }
38 | androidx-compose-material-iconsExtended = { group = "androidx.compose.material", name = "material-icons-extended", version.ref = "androidxCompose" }
39 | androidx-compose-material = { group = "androidx.compose.material", name = "material", version.ref = "androidxCompose" }
40 | androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "androidxComposeMaterial3" }
41 | androidx-compose-runtime = { group = "androidx.compose.runtime", name = "runtime", version.ref = "androidxCompose" }
42 | androidx-compose-ui = { group = "androidx.compose.ui", name = "ui", version.ref = "androidxCompose" }
43 | androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling", version.ref = "androidxCompose" }
44 | androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview", version.ref = "androidxCompose" }
45 | androidx-lifecycle-runtime = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "androidxLifecycle" }
46 | androidx-lifecycle-common = { group = "androidx.lifecycle", name = "lifecycle-common", version.ref = "androidxLifecycle" }
47 | androidx-lifecycle-runtimeCompose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "androidxLifecycle" }
48 | androidx-lifecycle-viewModelCompose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "androidxLifecycle" }
49 | androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "androidxLifecycle" }
50 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "androidxCore" }
51 | androidx-profileinstaller = { group = "androidx.profileinstaller", name = "profileinstaller", version.ref = "androidxProfileinstaller" }
52 | androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = "androidxTest" }
53 | androidx-test-rules = { group = "androidx.test", name = "rules", version.ref = "androidxTest" }
54 | hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
55 | hilt-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" }
56 | hilt-android-testing = { group = "com.google.dagger", name = "hilt-android-testing", version.ref = "hilt" }
57 | kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }
58 | kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" }
59 | kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
60 | kotlinx-reflect = { group = "org.jetbrains.kotlin", name = "kotlin-reflect", version.ref = "kotlin" }
61 | kotlinx-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" }
62 | kotlinx-test-junit5 = { group = "org.jetbrains.kotlin", name = "kotlin-test-junit5", version.ref = "kotlin" }
63 | okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
64 | sandwich = { group = "com.github.skydoves", name = "sandwich-retrofit", version.ref = "sandwich" }
65 | retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
66 | retrofit-kotlinx-serialization = { module = "com.squareup.retrofit2:converter-kotlinx-serialization", version.ref = "retrofit" }
67 | junit = { group = "junit", name = "junit", version.ref = "junit" }
68 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
69 | androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
70 | androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
71 | material = { group = "com.google.android.material", name = "material", version.ref = "material" }
72 | turbine = { module = "app.cash.turbine:turbine", version.ref = "turbine" }
73 |
74 | [plugins]
75 | android-application = { id = "com.android.application", version.ref = "agp" }
76 | android-library = { id = "com.android.library", version.ref = "agp" }
77 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
78 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
79 | ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
80 | compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
81 | nexus-plugin = { id = "com.vanniktech.maven.publish", version.ref = "nexusPlugin" }
82 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
83 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" }
84 | kotlin-binary-compatibility = { id = "org.jetbrains.kotlinx.binary-compatibility-validator", version.ref = "kotlinBinaryCompatibility" }
85 | spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/skydoves/flow-operators/7a7555c5131d714c1653e3a204c7ece38fca5907/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Sep 20 10:37:01 KST 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or 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 UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/scripts/publish-module.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.skydoves.flow.operators.Configuration
2 |
3 | apply(plugin = "com.vanniktech.maven.publish")
4 |
5 | rootProject.extra.apply {
6 | val snapshot = System.getenv("SNAPSHOT").toBoolean()
7 | val libVersion = if (snapshot) {
8 | Configuration.snapshotVersionName
9 | } else {
10 | Configuration.versionName
11 | }
12 | set("libVersion", libVersion)
13 | }
14 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | }
21 |
22 | rootProject.name = "flow-operators"
23 | include(":app")
24 | include(":flow-operators")
25 |
--------------------------------------------------------------------------------
/spotless/copyright.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | */
--------------------------------------------------------------------------------
/spotless/copyright.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * Designed and developed by 2025 skydoves (Jaewoong Eum)
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 | */
--------------------------------------------------------------------------------
/spotless/copyright.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
--------------------------------------------------------------------------------