├── .yarnrc
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── composeApp
├── desktopAppIcons
│ ├── LinuxIcon.png
│ ├── MacosIcon.icns
│ └── WindowsIcon.ico
├── src
│ ├── jsMain
│ │ ├── resources
│ │ │ ├── favicon.ico
│ │ │ ├── favicon-16x16.png
│ │ │ ├── favicon-32x32.png
│ │ │ ├── apple-touch-icon.png
│ │ │ ├── android-chrome-192x192.png
│ │ │ ├── android-chrome-512x512.png
│ │ │ ├── manifest.json
│ │ │ └── index.html
│ │ └── kotlin
│ │ │ ├── com
│ │ │ └── github
│ │ │ │ └── terrakok
│ │ │ │ └── flowmarbles
│ │ │ │ └── theme
│ │ │ │ └── Theme.js.kt
│ │ │ └── main.kt
│ ├── jvmMain
│ │ └── kotlin
│ │ │ ├── com
│ │ │ └── github
│ │ │ │ └── terrakok
│ │ │ │ └── flowmarbles
│ │ │ │ └── theme
│ │ │ │ └── Theme.jvm.kt
│ │ │ └── main.kt
│ └── commonMain
│ │ ├── composeResources
│ │ └── drawable
│ │ │ ├── ic_dark_mode.xml
│ │ │ ├── refresh.xml
│ │ │ ├── coffee.xml
│ │ │ ├── document.xml
│ │ │ └── ic_light_mode.xml
│ │ └── kotlin
│ │ └── com
│ │ └── github
│ │ └── terrakok
│ │ └── flowmarbles
│ │ ├── EventData.kt
│ │ ├── FilterOperators.kt
│ │ ├── FlowCase.kt
│ │ ├── theme
│ │ ├── Color.kt
│ │ └── Theme.kt
│ │ ├── TransformationOperators.kt
│ │ ├── CombinationOperators.kt
│ │ ├── EventFlowView.kt
│ │ └── App.kt
└── build.gradle.kts
├── .gitignore
├── gradle.properties
├── README.MD
├── .github
└── workflows
│ └── deploy.yaml
├── settings.gradle.kts
├── gradlew.bat
└── gradlew
/.yarnrc:
--------------------------------------------------------------------------------
1 | --install.mutex network
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/composeApp/desktopAppIcons/LinuxIcon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/desktopAppIcons/LinuxIcon.png
--------------------------------------------------------------------------------
/composeApp/desktopAppIcons/MacosIcon.icns:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/desktopAppIcons/MacosIcon.icns
--------------------------------------------------------------------------------
/composeApp/desktopAppIcons/WindowsIcon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/desktopAppIcons/WindowsIcon.ico
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/favicon.ico
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/favicon-16x16.png
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/favicon-32x32.png
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/apple-touch-icon.png
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/android-chrome-192x192.png
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/terrakok/FlowMarbles/HEAD/composeApp/src/jsMain/resources/android-chrome-512x512.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | *.iml
3 | .gradle
4 | .idea
5 | .kotlin
6 | .DS_Store
7 | build
8 | */build
9 | captures
10 | .externalNativeBuild
11 | .cxx
12 | local.properties
13 | xcuserdata/
14 | Pods/
15 | *.jks
16 | *.gpg
17 | *yarn.lock
18 |
--------------------------------------------------------------------------------
/composeApp/src/jsMain/kotlin/com/github/terrakok/flowmarbles/theme/Theme.js.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles.theme
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | @Composable
6 | internal actual fun SystemAppearance(isDark: Boolean) {
7 | }
--------------------------------------------------------------------------------
/composeApp/src/jvmMain/kotlin/com/github/terrakok/flowmarbles/theme/Theme.jvm.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles.theme
2 |
3 | import androidx.compose.runtime.Composable
4 |
5 | @Composable
6 | internal actual fun SystemAppearance(isDark: Boolean) {
7 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Gradle
2 | org.gradle.jvmargs=-Xmx4G
3 | org.gradle.caching=true
4 | org.gradle.configuration-cache=true
5 | org.gradle.daemon=true
6 | org.gradle.parallel=true
7 |
8 | #Kotlin
9 | kotlin.code.style=official
10 | kotlin.daemon.jvmargs=-Xmx4G
11 | kotlin.native.binary.gc=cms
12 | kotlin.incremental.wasm=true
13 |
14 | #Android
15 | android.useAndroidX=true
16 | android.nonTransitiveRClass=true
17 |
18 | #Compose
19 | org.jetbrains.compose.experimental.jscanvas.enabled=true
20 |
--------------------------------------------------------------------------------
/composeApp/src/jsMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.ExperimentalComposeUiApi
2 | import androidx.compose.ui.window.ComposeViewport
3 | import com.github.terrakok.flowmarbles.App
4 | import org.jetbrains.skiko.wasm.onWasmReady
5 | import kotlinx.browser.document
6 |
7 | @OptIn(ExperimentalComposeUiApi::class)
8 | fun main() {
9 | onWasmReady {
10 | val body = document.body ?: return@onWasmReady
11 | ComposeViewport(body) {
12 | App()
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Multiplatform App",
3 | "short_name": "Multiplatform App",
4 | "icons": [
5 | {
6 | "src": "./android-chrome-192x192.png",
7 | "sizes": "192x192",
8 | "type": "image/png"
9 | },
10 | {
11 | "src": "./android-chrome-512x512.png",
12 | "sizes": "512x512",
13 | "type": "image/png"
14 | }
15 | ],
16 | "theme_color": "#ffffff",
17 | "background_color": "#ffffff",
18 | "display": "standalone"
19 | }
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | # FlowMarbles
2 |
3 | Interactive diagrams of Kotlinx.coroutines Flow
4 |
5 | https://terrakok.github.io/FlowMarbles/
6 |
7 |
8 |
9 | ## ☕ Support the Developer
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/composeResources/drawable/ic_dark_mode.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
--------------------------------------------------------------------------------
/composeApp/src/jvmMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.unit.dp
2 | import androidx.compose.ui.window.Window
3 | import androidx.compose.ui.window.application
4 | import androidx.compose.ui.window.rememberWindowState
5 | import java.awt.Dimension
6 | import com.github.terrakok.flowmarbles.App
7 |
8 | fun main() = application {
9 | Window(
10 | title = "FlowMarbles",
11 | state = rememberWindowState(width = 800.dp, height = 600.dp),
12 | onCloseRequest = ::exitApplication,
13 | ) {
14 | window.minimumSize = Dimension(350, 600)
15 | App()
16 | }
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/composeResources/drawable/refresh.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/.github/workflows/deploy.yaml:
--------------------------------------------------------------------------------
1 | name: Deploy Web App
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 |
8 | permissions:
9 | contents: write
10 |
11 | jobs:
12 | deploy:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Checkout
16 | uses: actions/checkout@v4
17 | with:
18 | fetch-depth: 0
19 |
20 | - name: Setup Java
21 | uses: actions/setup-java@v4
22 | with:
23 | distribution: 'temurin'
24 | java-version: '17'
25 |
26 | - uses: gradle/actions/setup-gradle@v4
27 | with:
28 | cache-encryption-key: ${{ secrets.GRADLE_CACHE_ENCRYPTION_KEY }}
29 |
30 | - name: Build
31 | run: ./gradlew jsBrowserDistribution
32 |
33 | - name: Deploy
34 | uses: JamesIves/github-pages-deploy-action@v4
35 | with:
36 | branch: gh-pages
37 | folder: composeApp/build/dist/js/productionExecutable
--------------------------------------------------------------------------------
/composeApp/src/jsMain/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | FlowMarbles
11 |
12 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 |
3 | kotlin = "2.2.0"
4 | compose = "1.8.2"
5 | hotReload = "1.0.0-beta03"
6 | kotlinx-coroutines = "1.10.2"
7 |
8 | [libraries]
9 |
10 | kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
11 | kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
12 | kotlinx-coroutines-swing = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-swing", version.ref = "kotlinx-coroutines" }
13 | kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
14 |
15 | [plugins]
16 |
17 | multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
18 | compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
19 | compose = { id = "org.jetbrains.compose", version.ref = "compose" }
20 | hotReload = { id = "org.jetbrains.compose.hot-reload", version.ref = "hotReload" }
21 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/composeResources/drawable/coffee.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "FlowMarbles"
2 |
3 | pluginManagement {
4 | repositories {
5 | google {
6 | content {
7 | includeGroupByRegex("com\\.android.*")
8 | includeGroupByRegex("com\\.google.*")
9 | includeGroupByRegex("androidx.*")
10 | includeGroupByRegex("android.*")
11 | }
12 | }
13 | gradlePluginPortal()
14 | mavenCentral()
15 | }
16 | }
17 |
18 | dependencyResolutionManagement {
19 | repositories {
20 | google {
21 | content {
22 | includeGroupByRegex("com\\.android.*")
23 | includeGroupByRegex("com\\.google.*")
24 | includeGroupByRegex("androidx.*")
25 | includeGroupByRegex("android.*")
26 | }
27 | }
28 | mavenCentral()
29 | }
30 | }
31 | plugins {
32 | //https://github.com/JetBrains/compose-hot-reload?tab=readme-ov-file#set-up-automatic-provisioning-of-the-jetbrains-runtime-jbr-via-gradle
33 | id("org.gradle.toolchains.foojay-resolver-convention").version("1.0.0")
34 | }
35 |
36 | include(":composeApp")
37 |
38 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/composeResources/drawable/document.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/composeResources/drawable/ic_light_mode.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
--------------------------------------------------------------------------------
/composeApp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat
2 | import org.jetbrains.compose.reload.gradle.ComposeHotRun
3 |
4 | plugins {
5 | alias(libs.plugins.multiplatform)
6 | alias(libs.plugins.compose.compiler)
7 | alias(libs.plugins.compose)
8 | alias(libs.plugins.hotReload)
9 | }
10 |
11 | kotlin {
12 | jvm()
13 |
14 | js {
15 | browser()
16 | binaries.executable()
17 | }
18 |
19 | sourceSets {
20 | commonMain.dependencies {
21 | implementation(compose.runtime)
22 | implementation(compose.foundation)
23 | implementation(compose.material3)
24 | implementation(compose.components.resources)
25 | implementation(compose.components.uiToolingPreview)
26 | implementation(libs.kotlinx.coroutines.core)
27 | implementation(libs.kotlinx.coroutines.test)
28 | }
29 |
30 | jvmMain.dependencies {
31 | implementation(compose.desktop.currentOs)
32 | implementation(libs.kotlinx.coroutines.swing)
33 | }
34 |
35 | }
36 | }
37 |
38 | compose.desktop {
39 | application {
40 | mainClass = "MainKt"
41 |
42 | nativeDistributions {
43 | targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
44 | packageName = "FlowMarbles"
45 | packageVersion = "1.0.0"
46 | macOS {
47 | bundleID = "com.github.terrakok.flowmarbles.desktopApp"
48 | }
49 | }
50 | }
51 | }
52 |
53 | tasks.withType().configureEach {
54 | mainClass = "MainKt"
55 | }
56 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/EventData.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.ui.graphics.Color
4 | import kotlinx.coroutines.coroutineScope
5 | import kotlinx.coroutines.delay
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.buffer
8 | import kotlinx.coroutines.flow.flow
9 | import kotlinx.coroutines.flow.map
10 | import kotlinx.coroutines.flow.toList
11 | import kotlinx.coroutines.launch
12 | import kotlinx.coroutines.test.StandardTestDispatcher
13 | import kotlinx.coroutines.test.TestCoroutineScheduler
14 |
15 | const val MAX_TIME = 1000L
16 |
17 | object Event {
18 | val PURPLE = Color(0xFF9c27b0)
19 | val BLUE = Color(0xFF5D6DE1)
20 | val YELLOW = Color(0xFFff9800)
21 | val RED = Color(0xFFf44336)
22 | val GREEN = Color(0xFF4caf50)
23 |
24 | data class Data(
25 | val time: Long,
26 | val value: Int,
27 | val color: Color
28 | )
29 | }
30 |
31 | fun List.asFlow() = flow {
32 | var prevTime = 0L
33 | this@asFlow.forEach { eventData ->
34 | delay(eventData.time - prevTime)
35 | prevTime = eventData.time
36 | emit(eventData)
37 | }
38 | }.buffer(2) //buffer is here because we want to show a moment of the production instead of the consumption.
39 | //the problem is noticable with ZIP operator, for example
40 |
41 | suspend fun Flow.asList(): List = coroutineScope {
42 | val scheduler = TestCoroutineScheduler()
43 | val testDispatcher = StandardTestDispatcher(scheduler)
44 | var result: List? = null
45 | launch(testDispatcher) {
46 | result = this@asList
47 | .map { it.copy(time = scheduler.currentTime) }
48 | .toList()
49 | }
50 | scheduler.advanceUntilIdle()
51 | result!!
52 | }
53 |
--------------------------------------------------------------------------------
/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 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo. 1>&2
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
48 | echo. 1>&2
49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
50 | echo location of your Java installation. 1>&2
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo. 1>&2
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
62 | echo. 1>&2
63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
64 | echo location of your Java installation. 1>&2
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/FilterOperators.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.remember
5 | import androidx.compose.ui.Modifier
6 | import kotlinx.coroutines.flow.debounce
7 | import kotlinx.coroutines.flow.distinctUntilChangedBy
8 | import kotlinx.coroutines.flow.drop
9 | import kotlinx.coroutines.flow.dropWhile
10 | import kotlinx.coroutines.flow.filter
11 | import kotlinx.coroutines.flow.sample
12 | import kotlinx.coroutines.flow.take
13 | import kotlinx.coroutines.flow.takeWhile
14 |
15 | @Composable
16 | fun FlowFilter(modifier: Modifier = Modifier) {
17 | FlowCase1(
18 | input1 = remember {
19 | generateMutableEvents(7, colors = listOf(Event.RED, Event.YELLOW))
20 | },
21 | operator = { f1 ->
22 | f1.filter { it.color != Event.RED }
23 | },
24 | text = "filter { it.color != RED }",
25 | modifier = modifier
26 | )
27 | }
28 |
29 | @Composable
30 | fun FlowDrop(modifier: Modifier = Modifier) {
31 | FlowCase1(
32 | input1 = remember { generateMutableEvents(7) },
33 | operator = { f1 ->
34 | f1.drop(3)
35 | },
36 | text = "drop(3)",
37 | modifier = modifier
38 | )
39 | }
40 |
41 | @Composable
42 | fun FlowDropWhile(modifier: Modifier = Modifier) {
43 | FlowCase1(
44 | input1 = remember { generateMutableEvents(7) },
45 | operator = { f1 ->
46 | f1.dropWhile { it.value < 3 }
47 | },
48 | text = "dropWhile { it.value < 3 }",
49 | modifier = modifier
50 | )
51 | }
52 |
53 | @Composable
54 | fun FlowTake(modifier: Modifier = Modifier) {
55 | FlowCase1(
56 | input1 = remember { generateMutableEvents(7) },
57 | operator = { f1 ->
58 | f1.take(5)
59 | },
60 | text = "take(5)",
61 | modifier = modifier
62 | )
63 | }
64 |
65 | @Composable
66 | fun FlowTakeWhile(modifier: Modifier = Modifier) {
67 | FlowCase1(
68 | input1 = remember { generateMutableEvents(7) },
69 | operator = { f1 ->
70 | f1.takeWhile { it.value < 5 }
71 | },
72 | text = "takeWhile { it.value < 5 }",
73 | modifier = modifier
74 | )
75 | }
76 |
77 | @Composable
78 | fun FlowDebounce(modifier: Modifier = Modifier) {
79 | FlowCase1(
80 | input1 = remember { generateMutableEvents(7) },
81 | operator = { f1 ->
82 | f1.debounce(200)
83 | },
84 | text = "debounce(200)",
85 | modifier = modifier
86 | )
87 | }
88 |
89 | @Composable
90 | fun FlowSample(modifier: Modifier = Modifier) {
91 | FlowCase1(
92 | input1 = remember { generateMutableEvents(7) },
93 | operator = { f1 ->
94 | f1.sample(200)
95 | },
96 | text = "sample(200)",
97 | modifier = modifier
98 | )
99 | }
100 |
101 | @Composable
102 | fun FlowDistinctUntilChangedBy(modifier: Modifier = Modifier) {
103 | FlowCase1(
104 | input1 = remember {
105 | generateMutableEvents(7, colors = listOf(Event.RED, Event.GREEN, Event.GREEN, Event.GREEN))
106 | },
107 | operator = { f1 ->
108 | f1.distinctUntilChangedBy { it.color }
109 | },
110 | text = "distinctUntilChangedBy { it.color }",
111 | modifier = modifier
112 | )
113 | }
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/FlowCase.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.fillMaxWidth
5 | import androidx.compose.foundation.layout.height
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.foundation.layout.wrapContentHeight
8 | import androidx.compose.material3.Card
9 | import androidx.compose.material3.MaterialTheme
10 | import androidx.compose.material3.Text
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.LaunchedEffect
13 | import androidx.compose.runtime.derivedStateOf
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.mutableStateOf
16 | import androidx.compose.runtime.remember
17 | import androidx.compose.runtime.setValue
18 | import androidx.compose.ui.Alignment
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.unit.dp
21 | import kotlinx.coroutines.flow.Flow
22 |
23 | @Composable
24 | fun FlowCaseCard(
25 | vararg inputs: List,
26 | text: String,
27 | result: List,
28 | modifier: Modifier = Modifier
29 | ) {
30 | Card(modifier) {
31 | Column(
32 | modifier = Modifier.padding(16.dp)
33 | ) {
34 | inputs.forEach { inputFlow ->
35 | EventFlowView(
36 | events = inputFlow,
37 | draggable = true,
38 | modifier = Modifier.fillMaxWidth().height(80.dp)
39 | )
40 | }
41 | Text(
42 | text = text,
43 | modifier = Modifier.wrapContentHeight().align(Alignment.CenterHorizontally).padding(16.dp),
44 | style = MaterialTheme.typography.titleMedium.copy()
45 | )
46 | EventFlowView(
47 | events = result,
48 | modifier = Modifier.fillMaxWidth().height(80.dp)
49 | )
50 | }
51 | }
52 | }
53 |
54 | @Composable
55 | fun FlowCase1(
56 | input1: List,
57 | operator: (Flow) -> Flow,
58 | text: String,
59 | modifier: Modifier = Modifier
60 | ) {
61 | val f1 by remember {
62 | derivedStateOf { input1.map { it.data.copy(time = it.timeState.value) }.sortedBy { it.time } }
63 | }
64 |
65 | var result by remember { mutableStateOf(emptyList()) }
66 | LaunchedEffect(f1) {
67 | result = operator(f1.asFlow()).asList().map { MutableEvent(it) }
68 | }
69 |
70 | FlowCaseCard(
71 | input1,
72 | text = text,
73 | result = result,
74 | modifier = modifier
75 | )
76 | }
77 |
78 |
79 | @Composable
80 | fun FlowCase2(
81 | input1: List,
82 | input2: List,
83 | operator: (Flow, Flow) -> Flow,
84 | text: String,
85 | modifier: Modifier = Modifier
86 | ) {
87 | val f1 by remember {
88 | derivedStateOf { input1.map { it.data.copy(time = it.timeState.value) }.sortedBy { it.time } }
89 | }
90 | val f2 by remember {
91 | derivedStateOf { input2.map { it.data.copy(time = it.timeState.value) }.sortedBy { it.time } }
92 | }
93 |
94 | var result by remember { mutableStateOf(emptyList()) }
95 | LaunchedEffect(f1, f2) {
96 | result = operator(f1.asFlow(), f2.asFlow()).asList().map { MutableEvent(it) }
97 | }
98 |
99 | FlowCaseCard(
100 | input1, input2,
101 | text = text,
102 | result = result,
103 | modifier = modifier
104 | )
105 | }
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | //generated by https://materialkolor.com
6 | //Color palette was taken here: https://coolors.co/palette/e63946-f1faee-a8dadc-457b9d-1d3557
7 |
8 | internal val Seed = Color(0xFF1D3557)
9 |
10 | internal val PrimaryLight = Color(0xFF485F84)
11 | internal val OnPrimaryLight = Color(0xFFFFFFFF)
12 | internal val PrimaryContainerLight = Color(0xFFD5E3FF)
13 | internal val OnPrimaryContainerLight = Color(0xFF30476A)
14 | internal val SecondaryLight = Color(0xFF2B6485)
15 | internal val OnSecondaryLight = Color(0xFFFFFFFF)
16 | internal val SecondaryContainerLight = Color(0xFFC7E7FF)
17 | internal val OnSecondaryContainerLight = Color(0xFF064C6B)
18 | internal val TertiaryLight = Color(0xFF356668)
19 | internal val OnTertiaryLight = Color(0xFFFFFFFF)
20 | internal val TertiaryContainerLight = Color(0xFFB9ECEE)
21 | internal val OnTertiaryContainerLight = Color(0xFF1A4E50)
22 | internal val ErrorLight = Color(0xFFBB152C)
23 | internal val OnErrorLight = Color(0xFFFFFFFF)
24 | internal val ErrorContainerLight = Color(0xFFFFDAD8)
25 | internal val OnErrorContainerLight = Color(0xFF410007)
26 | internal val BackgroundLight = Color(0xFFF9F9F9)
27 | internal val OnBackgroundLight = Color(0xFF1A1C1C)
28 | internal val SurfaceLight = Color(0xFFF9F9F9)
29 | internal val OnSurfaceLight = Color(0xFF1A1C1C)
30 | internal val SurfaceVariantLight = Color(0xFFDCE5D9)
31 | internal val OnSurfaceVariantLight = Color(0xFF404941)
32 | internal val OutlineLight = Color(0xFF717970)
33 | internal val OutlineVariantLight = Color(0xFFC0C9BE)
34 | internal val ScrimLight = Color(0xFF000000)
35 | internal val InverseSurfaceLight = Color(0xFF2F3131)
36 | internal val InverseOnSurfaceLight = Color(0xFFF0F1F1)
37 | internal val InversePrimaryLight = Color(0xFFB0C7F1)
38 | internal val SurfaceDimLight = Color(0xFFDADADA)
39 | internal val SurfaceBrightLight = Color(0xFFF9F9F9)
40 | internal val SurfaceContainerLowestLight = Color(0xFFFFFFFF)
41 | internal val SurfaceContainerLowLight = Color(0xFFF3F3F4)
42 | internal val SurfaceContainerLight = Color(0xFFEEEEEE)
43 | internal val SurfaceContainerHighLight = Color(0xFFE8E8E8)
44 | internal val SurfaceContainerHighestLight = Color(0xFFE2E2E2)
45 |
46 | internal val PrimaryDark = Color(0xFFB0C7F1)
47 | internal val OnPrimaryDark = Color(0xFF183153)
48 | internal val PrimaryContainerDark = Color(0xFF30476A)
49 | internal val OnPrimaryContainerDark = Color(0xFFD5E3FF)
50 | internal val SecondaryDark = Color(0xFF98CDF2)
51 | internal val OnSecondaryDark = Color(0xFF00344C)
52 | internal val SecondaryContainerDark = Color(0xFF064C6B)
53 | internal val OnSecondaryContainerDark = Color(0xFFC7E7FF)
54 | internal val TertiaryDark = Color(0xFF9ECFD1)
55 | internal val OnTertiaryDark = Color(0xFF003739)
56 | internal val TertiaryContainerDark = Color(0xFF1A4E50)
57 | internal val OnTertiaryContainerDark = Color(0xFFB9ECEE)
58 | internal val ErrorDark = Color(0xFFFFB3B1)
59 | internal val OnErrorDark = Color(0xFF680011)
60 | internal val ErrorContainerDark = Color(0xFF92001C)
61 | internal val OnErrorContainerDark = Color(0xFFFFDAD8)
62 | internal val BackgroundDark = Color(0xFF121414)
63 | internal val OnBackgroundDark = Color(0xFFE2E2E2)
64 | internal val SurfaceDark = Color(0xFF121414)
65 | internal val OnSurfaceDark = Color(0xFFE2E2E2)
66 | internal val SurfaceVariantDark = Color(0xFF404941)
67 | internal val OnSurfaceVariantDark = Color(0xFFC0C9BE)
68 | internal val OutlineDark = Color(0xFF8A9389)
69 | internal val OutlineVariantDark = Color(0xFF404941)
70 | internal val ScrimDark = Color(0xFF000000)
71 | internal val InverseSurfaceDark = Color(0xFFE2E2E2)
72 | internal val InverseOnSurfaceDark = Color(0xFF2F3131)
73 | internal val InversePrimaryDark = Color(0xFF485F84)
74 | internal val SurfaceDimDark = Color(0xFF121414)
75 | internal val SurfaceBrightDark = Color(0xFF37393A)
76 | internal val SurfaceContainerLowestDark = Color(0xFF0C0F0F)
77 | internal val SurfaceContainerLowDark = Color(0xFF1A1C1C)
78 | internal val SurfaceContainerDark = Color(0xFF1E2020)
79 | internal val SurfaceContainerHighDark = Color(0xFF282A2B)
80 | internal val SurfaceContainerHighestDark = Color(0xFF333535)
81 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material3.MaterialTheme
5 | import androidx.compose.material3.Surface
6 | import androidx.compose.material3.darkColorScheme
7 | import androidx.compose.material3.lightColorScheme
8 | import androidx.compose.runtime.*
9 |
10 | private val LightColorScheme = lightColorScheme(
11 | primary = PrimaryLight,
12 | onPrimary = OnPrimaryLight,
13 | primaryContainer = PrimaryContainerLight,
14 | onPrimaryContainer = OnPrimaryContainerLight,
15 | secondary = SecondaryLight,
16 | onSecondary = OnSecondaryLight,
17 | secondaryContainer = SecondaryContainerLight,
18 | onSecondaryContainer = OnSecondaryContainerLight,
19 | tertiary = TertiaryLight,
20 | onTertiary = OnTertiaryLight,
21 | tertiaryContainer = TertiaryContainerLight,
22 | onTertiaryContainer = OnTertiaryContainerLight,
23 | error = ErrorLight,
24 | onError = OnErrorLight,
25 | errorContainer = ErrorContainerLight,
26 | onErrorContainer = OnErrorContainerLight,
27 | background = BackgroundLight,
28 | onBackground = OnBackgroundLight,
29 | surface = SurfaceLight,
30 | onSurface = OnSurfaceLight,
31 | surfaceVariant = SurfaceVariantLight,
32 | onSurfaceVariant = OnSurfaceVariantLight,
33 | outline = OutlineLight,
34 | outlineVariant = OutlineVariantLight,
35 | scrim = ScrimLight,
36 | inverseSurface = InverseSurfaceLight,
37 | inverseOnSurface = InverseOnSurfaceLight,
38 | inversePrimary = InversePrimaryLight,
39 | surfaceDim = SurfaceDimLight,
40 | surfaceBright = SurfaceBrightLight,
41 | surfaceContainerLowest = SurfaceContainerLowestLight,
42 | surfaceContainerLow = SurfaceContainerLowLight,
43 | surfaceContainer = SurfaceContainerLight,
44 | surfaceContainerHigh = SurfaceContainerHighLight,
45 | surfaceContainerHighest = SurfaceContainerHighestLight,
46 | )
47 |
48 | private val DarkColorScheme = darkColorScheme(
49 | primary = PrimaryDark,
50 | onPrimary = OnPrimaryDark,
51 | primaryContainer = PrimaryContainerDark,
52 | onPrimaryContainer = OnPrimaryContainerDark,
53 | secondary = SecondaryDark,
54 | onSecondary = OnSecondaryDark,
55 | secondaryContainer = SecondaryContainerDark,
56 | onSecondaryContainer = OnSecondaryContainerDark,
57 | tertiary = TertiaryDark,
58 | onTertiary = OnTertiaryDark,
59 | tertiaryContainer = TertiaryContainerDark,
60 | onTertiaryContainer = OnTertiaryContainerDark,
61 | error = ErrorDark,
62 | onError = OnErrorDark,
63 | errorContainer = ErrorContainerDark,
64 | onErrorContainer = OnErrorContainerDark,
65 | background = BackgroundDark,
66 | onBackground = OnBackgroundDark,
67 | surface = SurfaceDark,
68 | onSurface = OnSurfaceDark,
69 | surfaceVariant = SurfaceVariantDark,
70 | onSurfaceVariant = OnSurfaceVariantDark,
71 | outline = OutlineDark,
72 | outlineVariant = OutlineVariantDark,
73 | scrim = ScrimDark,
74 | inverseSurface = InverseSurfaceDark,
75 | inverseOnSurface = InverseOnSurfaceDark,
76 | inversePrimary = InversePrimaryDark,
77 | surfaceDim = SurfaceDimDark,
78 | surfaceBright = SurfaceBrightDark,
79 | surfaceContainerLowest = SurfaceContainerLowestDark,
80 | surfaceContainerLow = SurfaceContainerLowDark,
81 | surfaceContainer = SurfaceContainerDark,
82 | surfaceContainerHigh = SurfaceContainerHighDark,
83 | surfaceContainerHighest = SurfaceContainerHighestDark,
84 | )
85 |
86 | internal val LocalThemeIsDark = compositionLocalOf { mutableStateOf(true) }
87 |
88 | @Composable
89 | internal fun AppTheme(
90 | content: @Composable () -> Unit
91 | ) {
92 | val systemIsDark = isSystemInDarkTheme()
93 | val isDarkState = remember(systemIsDark) { mutableStateOf(systemIsDark) }
94 | CompositionLocalProvider(
95 | LocalThemeIsDark provides isDarkState
96 | ) {
97 | val isDark by isDarkState
98 | SystemAppearance(!isDark)
99 | MaterialTheme(
100 | colorScheme = if (isDark) DarkColorScheme else LightColorScheme,
101 | content = { Surface(content = content) }
102 | )
103 | }
104 | }
105 |
106 | @Composable
107 | internal expect fun SystemAppearance(isDark: Boolean)
108 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/TransformationOperators.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.remember
5 | import androidx.compose.ui.Modifier
6 | import kotlinx.coroutines.delay
7 | import kotlinx.coroutines.flow.map
8 | import kotlinx.coroutines.flow.mapLatest
9 | import kotlinx.coroutines.flow.runningReduce
10 | import kotlinx.coroutines.flow.transform
11 | import kotlinx.coroutines.flow.transformLatest
12 | import kotlinx.coroutines.flow.transformWhile
13 | import kotlinx.coroutines.flow.withIndex
14 | import kotlin.random.Random
15 |
16 |
17 | @Composable
18 | fun FlowMap(modifier: Modifier = Modifier) {
19 | FlowCase1(
20 | input1 = remember { generateMutableEvents() },
21 | operator = { f1 ->
22 | f1.map { it.copy(color = Event.YELLOW) }
23 | },
24 | text = "map { it.copy(color = YELLOW) }",
25 | modifier = modifier
26 | )
27 | }
28 |
29 | @Composable
30 | fun FlowMapLatest(modifier: Modifier = Modifier) {
31 | FlowCase1(
32 | input1 = remember { generateMutableEvents() },
33 | operator = { f1 ->
34 | f1.mapLatest {
35 | delay(200)
36 | it.copy(color = Event.YELLOW)
37 | }
38 | },
39 | text = """
40 | mapLatest {
41 | delay(200)
42 | it.copy(color = YELLOW)
43 | }
44 | """.trimIndent(),
45 | modifier = modifier
46 | )
47 | }
48 |
49 | @Composable
50 | fun FlowTransform(modifier: Modifier = Modifier) {
51 | FlowCase1(
52 | input1 = remember { generateMutableEvents() },
53 | operator = { f1 ->
54 | f1.transform {
55 | emit(it.copy(color = Event.YELLOW))
56 | delay(100)
57 | emit(it.copy(color = Event.GREEN))
58 | }
59 | },
60 | text = """
61 | transform {
62 | emit(it.copy(color = YELLOW))
63 | delay(100)
64 | emit(it.copy(color = GREEN))
65 | }
66 | """.trimIndent(),
67 | modifier = modifier
68 | )
69 | }
70 |
71 | @Composable
72 | fun FlowTransformLatest(modifier: Modifier = Modifier) {
73 | FlowCase1(
74 | input1 = remember { generateMutableEvents() },
75 | operator = { f1 ->
76 | f1.transformLatest {
77 | emit(it.copy(color = Event.YELLOW))
78 | delay(100)
79 | emit(it.copy(color = Event.GREEN))
80 | }
81 | },
82 | text = """
83 | transformLatest {
84 | emit(it.copy(color = YELLOW))
85 | delay(100)
86 | emit(it.copy(color = GREEN))
87 | }
88 | """.trimIndent(),
89 | modifier = modifier
90 | )
91 | }
92 |
93 | @Composable
94 | fun FlowTransformWhile(modifier: Modifier = Modifier) {
95 | FlowCase1(
96 | input1 = remember { generateMutableEvents() },
97 | operator = { f1 ->
98 | f1.transformWhile {
99 | delay(100)
100 | emit(it.copy(color = Event.PURPLE))
101 | it.value < 2
102 | }
103 | },
104 | text = """
105 | transformWhile {
106 | delay(100)
107 | emit(it.copy(color = PURPLE))
108 | it.value < 2
109 | }
110 | """.trimIndent(),
111 | modifier = modifier
112 | )
113 | }
114 |
115 | @Composable
116 | fun FlowWithIndex(modifier: Modifier = Modifier) {
117 | FlowCase1(
118 | input1 = remember { generateMutableEvents(value = { Random.nextInt(3, 30) }) },
119 | operator = { f1 ->
120 | f1.withIndex().map { (index, value) -> value.copy(value = index) }
121 | },
122 | text = "withIndex().map { (index, value) -> value.copy(value = index) }",
123 | modifier = modifier
124 | )
125 | }
126 |
127 | @Composable
128 | fun FlowRunningReduce(modifier: Modifier = Modifier) {
129 | FlowCase1(
130 | input1 = remember { generateMutableEvents() },
131 | operator = { f1 ->
132 | f1.runningReduce { acc, value ->
133 | acc.copy(value = acc.value + value.value)
134 | }
135 | },
136 | text = """
137 | runningReduce { acc, value ->
138 | acc.copy(value = acc.value + value.value)
139 | }
140 | """.trimIndent(),
141 | modifier = modifier
142 | )
143 | }
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/CombinationOperators.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.remember
5 | import androidx.compose.ui.Modifier
6 | import kotlinx.coroutines.flow.combine
7 | import kotlinx.coroutines.flow.flatMapConcat
8 | import kotlinx.coroutines.flow.flatMapLatest
9 | import kotlinx.coroutines.flow.flatMapMerge
10 | import kotlinx.coroutines.flow.map
11 | import kotlinx.coroutines.flow.merge
12 | import kotlinx.coroutines.flow.zip
13 | import kotlin.math.max
14 |
15 | @Composable
16 | fun FlowMerge(modifier: Modifier = Modifier) {
17 | FlowCase2(
18 | input1 = remember { generateMutableEvents(3) },
19 | input2 = remember {
20 | generateMutableEvents(
21 | count = 3,
22 | colors = listOf(Event.GREEN),
23 | )
24 | },
25 | operator = { f1, f2 ->
26 | merge(f1, f2)
27 | },
28 | text = "merge(flowA, flowB)",
29 | modifier = modifier
30 | )
31 | }
32 |
33 | @Composable
34 | fun FlowCombine(modifier: Modifier = Modifier) {
35 | FlowCase2(
36 | input1 = remember { generateMutableEvents(3) },
37 | input2 = remember {
38 | generateMutableEvents(
39 | count = 3,
40 | colors = listOf(Event.GREEN, Event.YELLOW, Event.BLUE),
41 | )
42 | },
43 | operator = { f1, f2 ->
44 | f1.combine(f2) { first, second ->
45 | Event.Data(
46 | time = 0,
47 | value = first.value + second.value,
48 | color = first.color,
49 | )
50 | }
51 | },
52 | text = """
53 | flowA.combine(flowB) { first, second -> Event(
54 | value = first.value + second.value,
55 | color = first.color
56 | ) }
57 | """.trimIndent(),
58 | modifier = modifier
59 | )
60 | }
61 |
62 | @Composable
63 | fun FlowZip(modifier: Modifier = Modifier) {
64 | FlowCase2(
65 | input1 = remember { generateMutableEvents(3) },
66 | input2 = remember {
67 | generateMutableEvents(
68 | count = 3,
69 | colors = listOf(Event.GREEN)
70 | )
71 | },
72 | operator = { f1, f2 ->
73 | f1.zip(f2) { first, second ->
74 | Event.Data(
75 | time = 0,
76 | value = first.value + second.value,
77 | color = first.color
78 | )
79 | }
80 | },
81 | text = """
82 | flowA.zip(flowB) { first, second -> Event(
83 | value = first.value + second.value,
84 | color = first.color
85 | ) }
86 | """.trimIndent(),
87 | modifier = modifier
88 | )
89 | }
90 |
91 | @Composable
92 | fun FlowFlatMapMerge(modifier: Modifier = Modifier) {
93 | FlowCase2(
94 | input1 = remember { generateMutableEvents(3) },
95 | input2 = remember {
96 | listOf(
97 | MutableEvent(Event.Data(10, 1, Event.PURPLE)),
98 | MutableEvent(Event.Data(70, 2, Event.PURPLE)),
99 | )
100 | },
101 | operator = { f1, f2 ->
102 | f1.flatMapMerge { f2 }
103 | },
104 | text = "flatMapMerge { f2 }",
105 | modifier = modifier
106 | )
107 | }
108 |
109 | @Composable
110 | fun FlowFlatMapConcat(modifier: Modifier = Modifier) {
111 | FlowCase2(
112 | input1 = remember { generateMutableEvents(3) },
113 | input2 = remember {
114 | listOf(
115 | MutableEvent(Event.Data(10, 1, Event.PURPLE)),
116 | MutableEvent(Event.Data(70, 2, Event.PURPLE)),
117 | )
118 | },
119 | operator = { f1, f2 ->
120 | f1.flatMapConcat { f2 }
121 | },
122 | text = "flatMapConcat { f2 }",
123 | modifier = modifier
124 | )
125 | }
126 |
127 | @Composable
128 | fun FlowFlatMapLatest(modifier: Modifier = Modifier) {
129 | FlowCase2(
130 | input1 = remember { generateMutableEvents(3) },
131 | input2 = remember {
132 | listOf(
133 | MutableEvent(Event.Data(10, 1, Event.PURPLE)),
134 | MutableEvent(Event.Data(70, 2, Event.PURPLE)),
135 | )
136 | },
137 | operator = { f1, f2 ->
138 | f1.flatMapLatest { f2 }
139 | },
140 | text = "flatMapLatest { f2 }",
141 | modifier = modifier
142 | )
143 | }
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/EventFlowView.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.foundation.Canvas
4 | import androidx.compose.foundation.gestures.Orientation
5 | import androidx.compose.foundation.gestures.draggable
6 | import androidx.compose.foundation.gestures.rememberDraggableState
7 | import androidx.compose.foundation.layout.Box
8 | import androidx.compose.foundation.layout.BoxWithConstraints
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.offset
11 | import androidx.compose.foundation.layout.size
12 | import androidx.compose.foundation.layout.wrapContentSize
13 | import androidx.compose.foundation.shape.CutCornerShape
14 | import androidx.compose.foundation.shape.RoundedCornerShape
15 | import androidx.compose.material3.MaterialTheme
16 | import androidx.compose.material3.Surface
17 | import androidx.compose.material3.Text
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.runtime.getValue
20 | import androidx.compose.runtime.mutableStateOf
21 | import androidx.compose.runtime.setValue
22 | import androidx.compose.ui.Alignment
23 | import androidx.compose.ui.Modifier
24 | import androidx.compose.ui.geometry.Offset
25 | import androidx.compose.ui.graphics.Color
26 | import androidx.compose.ui.graphics.StrokeCap
27 | import androidx.compose.ui.platform.LocalDensity
28 | import androidx.compose.ui.unit.dp
29 | import com.github.terrakok.flowmarbles.Event.BLUE
30 | import com.github.terrakok.flowmarbles.Event.Data
31 | import kotlin.random.Random
32 |
33 | data class MutableEvent(val data: Event.Data) {
34 | val timeState = mutableStateOf(data.time)
35 | }
36 |
37 |
38 | fun generateMutableEvents(
39 | count: Int = 5,
40 | colors: List = listOf(BLUE),
41 | value: (Int) -> Int = { it }
42 | ): List = (1..count)
43 | .map { Random.nextLong(0, MAX_TIME) }
44 | .sorted()
45 | .mapIndexed { i, v ->
46 | MutableEvent(
47 | Data(v, value(i), colors[i % colors.size])
48 | )
49 | }
50 |
51 | @Composable
52 | fun EventFlowView(
53 | events: List,
54 | draggable: Boolean = false,
55 | modifier: Modifier = Modifier
56 | ) {
57 | val lineColor = MaterialTheme.colorScheme.onSurface
58 | val eventSize = 40.dp
59 |
60 | BoxWithConstraints(
61 | modifier = modifier
62 | ) {
63 | val arrowWidth = 12.dp
64 | val arrowWidthPx = with(LocalDensity.current) { arrowWidth.toPx() }
65 |
66 | Canvas(
67 | modifier = Modifier.fillMaxSize()
68 | ) {
69 | drawLine(
70 | color = lineColor,
71 | start = Offset(0f, size.height / 2),
72 | end = Offset(size.width, size.height / 2),
73 | strokeWidth = 4f,
74 | cap = StrokeCap.Round
75 | )
76 | drawLine(
77 | color = lineColor,
78 | start = Offset(size.width, size.height / 2),
79 | end = Offset(size.width - arrowWidthPx, (size.height - arrowWidthPx) / 2),
80 | strokeWidth = 4f,
81 | cap = StrokeCap.Round
82 | )
83 | drawLine(
84 | color = lineColor,
85 | start = Offset(size.width, size.height / 2),
86 | end = Offset(size.width - arrowWidthPx, (size.height + arrowWidthPx) / 2),
87 | strokeWidth = 4f,
88 | cap = StrokeCap.Round
89 | )
90 | drawLine(
91 | color = lineColor,
92 | start = Offset(arrowWidthPx, (size.height - arrowWidthPx) / 2),
93 | end = Offset(arrowWidthPx, (size.height + arrowWidthPx) / 2),
94 | strokeWidth = 4f,
95 | cap = StrokeCap.Round
96 | )
97 | }
98 |
99 | val availableWidth = with(LocalDensity.current) {
100 | (maxWidth - arrowWidth * 2).toPx()
101 | }
102 | // Draw circles for each event
103 | events.forEachIndexed { index, event ->
104 | var eventTime by event.timeState
105 | val xPos = arrowWidthPx + (availableWidth * (eventTime.toFloat() / MAX_TIME))
106 |
107 | Box(
108 | modifier = Modifier
109 | .offset(
110 | x = with(LocalDensity.current) { xPos.toDp() - eventSize / 2 },
111 | y = maxHeight / 2 - eventSize / 2
112 | )
113 | .size(eventSize)
114 | .draggable(
115 | enabled = draggable,
116 | orientation = Orientation.Horizontal,
117 | state = rememberDraggableState { delta ->
118 | val minOffset = -xPos + arrowWidthPx
119 | val maxOffset = availableWidth - xPos
120 | val offsetX = delta.coerceIn(minOffset, maxOffset)
121 | eventTime = ((xPos + offsetX - arrowWidthPx) * MAX_TIME / availableWidth).toLong()
122 | }
123 | )
124 | ) {
125 | Surface(
126 | modifier = Modifier.fillMaxSize(),
127 | color = event.data.color,
128 | shape = when (event.data.color) {
129 | Event.BLUE -> RoundedCornerShape(50)
130 | Event.YELLOW -> CutCornerShape(50)
131 | Event.RED -> CutCornerShape(25)
132 | Event.PURPLE -> CutCornerShape(0)
133 | else -> RoundedCornerShape(25)
134 | },
135 | shadowElevation = 4.dp,
136 | ) {
137 | Text(
138 | text = event.data.value.toString(),
139 | color = Color.White,
140 | modifier = Modifier.align(Alignment.Center).wrapContentSize(),
141 | style = MaterialTheme.typography.labelSmall.copy(),
142 | )
143 | }
144 | }
145 | }
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/composeApp/src/commonMain/kotlin/com/github/terrakok/flowmarbles/App.kt:
--------------------------------------------------------------------------------
1 | package com.github.terrakok.flowmarbles
2 |
3 | import androidx.compose.foundation.horizontalScroll
4 | import androidx.compose.foundation.layout.Arrangement
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.Row
8 | import androidx.compose.foundation.layout.Spacer
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.height
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.layout.width
14 | import androidx.compose.foundation.rememberScrollState
15 | import androidx.compose.foundation.verticalScroll
16 | import androidx.compose.material3.FilterChip
17 | import androidx.compose.material3.Icon
18 | import androidx.compose.material3.IconButton
19 | import androidx.compose.material3.MaterialTheme
20 | import androidx.compose.material3.Text
21 | import androidx.compose.runtime.Composable
22 | import androidx.compose.runtime.MutableState
23 | import androidx.compose.runtime.getValue
24 | import androidx.compose.runtime.mutableStateOf
25 | import androidx.compose.runtime.remember
26 | import androidx.compose.runtime.setValue
27 | import androidx.compose.ui.Alignment
28 | import androidx.compose.ui.Modifier
29 | import androidx.compose.ui.layout.layout
30 | import androidx.compose.ui.layout.onGloballyPositioned
31 | import androidx.compose.ui.platform.LocalDensity
32 | import androidx.compose.ui.platform.LocalUriHandler
33 | import androidx.compose.ui.unit.dp
34 | import com.github.terrakok.flowmarbles.theme.AppTheme
35 | import com.github.terrakok.flowmarbles.theme.LocalThemeIsDark
36 | import flowmarbles.composeapp.generated.resources.Res
37 | import flowmarbles.composeapp.generated.resources.coffee
38 | import flowmarbles.composeapp.generated.resources.document
39 | import flowmarbles.composeapp.generated.resources.ic_dark_mode
40 | import flowmarbles.composeapp.generated.resources.ic_light_mode
41 | import org.jetbrains.compose.resources.painterResource
42 | import org.jetbrains.compose.ui.tooling.preview.Preview
43 |
44 | @Preview
45 | @Composable
46 | internal fun App() = AppTheme {
47 | Box(
48 | modifier = Modifier.fillMaxSize(),
49 | contentAlignment = Alignment.TopCenter,
50 | ) {
51 | val minW = with(LocalDensity.current) { 750.dp.roundToPx() }
52 | val maxW = with(LocalDensity.current) { 1000.dp.roundToPx() }
53 | var containerWidth by remember { mutableStateOf(minW) }
54 | Column(
55 | modifier = Modifier
56 | .fillMaxWidth()
57 | .onGloballyPositioned { containerWidth = it.size.width }
58 | .verticalScroll(rememberScrollState())
59 | .horizontalScroll(rememberScrollState())
60 | .layout { m, c ->
61 | val minC = containerWidth.coerceIn(minW, maxW)
62 | val placeable = m.measure(
63 | c.copy(minWidth = minC, minHeight = 0, maxWidth = minC, maxHeight = Int.MAX_VALUE)
64 | )
65 | layout(placeable.width, placeable.height) {
66 | placeable.place(0, 0)
67 | }
68 | }
69 | .padding(40.dp)
70 | ) {
71 | Row(
72 | verticalAlignment = Alignment.Bottom,
73 | ) {
74 | Text(
75 | text = "Flow Marbles",
76 | style = MaterialTheme.typography.displayLarge
77 | )
78 | Spacer(modifier = Modifier.weight(1f))
79 |
80 | val uriHandler = LocalUriHandler.current
81 | IconButton(
82 | onClick = { uriHandler.openUri("https://www.buymeacoffee.com/terrakok") },
83 | ) {
84 | Icon(
85 | painter = painterResource(Res.drawable.coffee),
86 | contentDescription = "BuyMeACoffee",
87 | tint = MaterialTheme.colorScheme.onBackground
88 | )
89 | }
90 | IconButton(
91 | onClick = { uriHandler.openUri("https://github.com/terrakok/FlowMarbles") },
92 | ) {
93 | Icon(
94 | painter = painterResource(Res.drawable.document),
95 | contentDescription = "GitHub",
96 | tint = MaterialTheme.colorScheme.onBackground
97 | )
98 | }
99 |
100 | var themeIsDark by LocalThemeIsDark.current
101 | IconButton(
102 | onClick = { themeIsDark = !themeIsDark },
103 | ) {
104 | Icon(
105 | painter = painterResource(
106 | if (themeIsDark) Res.drawable.ic_light_mode else Res.drawable.ic_dark_mode
107 | ),
108 | contentDescription = "Theme",
109 | tint = MaterialTheme.colorScheme.onBackground
110 | )
111 | }
112 | }
113 | Text(
114 | text = "Interactive diagrams of Kotlinx.coroutines Flow",
115 | style = MaterialTheme.typography.headlineMedium
116 | )
117 | Spacer(modifier = Modifier.height(40.dp))
118 | Row {
119 |
120 | val filterItems = remember {
121 | listOf(
122 | Operator("Filter", mutableStateOf(true)) { FlowFilter() },
123 | Operator("Drop") { FlowDrop() },
124 | Operator("DropWhile") { FlowDropWhile() },
125 | Operator("Take") { FlowTake() },
126 | Operator("TakeWhile") { FlowTakeWhile() },
127 | Operator("Debounce") { FlowDebounce() },
128 | Operator("Sample") { FlowSample() },
129 | Operator("DistinctUntilChanged") { FlowDistinctUntilChangedBy() },
130 | )
131 | }
132 |
133 | val transformationItems = remember {
134 | listOf(
135 | Operator("Map") { FlowMap() },
136 | Operator("MapLatest") { FlowMapLatest() },
137 | Operator("Transform") { FlowTransform() },
138 | Operator("TransformLatest") { FlowTransformLatest() },
139 | Operator("TransformWhile") { FlowTransformWhile() },
140 | Operator("WithIndex") { FlowWithIndex() },
141 | Operator("RunningReduce") { FlowRunningReduce() },
142 | )
143 | }
144 |
145 | val combinationItems = remember {
146 | listOf(
147 | Operator("Merge", mutableStateOf(true)) { FlowMerge() },
148 | Operator("Combine") { FlowCombine() },
149 | Operator("Zip") { FlowZip() },
150 | Operator("FlatMapMerge") { FlowFlatMapMerge() },
151 | Operator("FlatMapConcat") { FlowFlatMapConcat() },
152 | Operator("FlatMapLatest") { FlowFlatMapLatest() },
153 |
154 | )
155 | }
156 |
157 | Column {
158 | Text(text = "Filter Operators", style = MaterialTheme.typography.labelLarge)
159 | filterItems.forEach { item -> OperatorChip(item) }
160 | Spacer(modifier = Modifier.height(16.dp))
161 | Text(text = "Transformation Operators", style = MaterialTheme.typography.labelLarge)
162 | transformationItems.forEach { item -> OperatorChip(item) }
163 | Spacer(modifier = Modifier.height(16.dp))
164 | Text(text = "Combination Operators", style = MaterialTheme.typography.labelLarge)
165 | combinationItems.forEach { item -> OperatorChip(item) }
166 | }
167 | Spacer(modifier = Modifier.width(16.dp))
168 | Column(
169 | horizontalAlignment = Alignment.CenterHorizontally,
170 | verticalArrangement = Arrangement.spacedBy(16.dp)
171 | ) {
172 | (filterItems + transformationItems + combinationItems).forEach { item ->
173 | if (item.enabled.value) { item.view() }
174 | }
175 | }
176 | }
177 | }
178 | }
179 | }
180 |
181 | data class Operator(
182 | val name: String,
183 | val enabled: MutableState = mutableStateOf(false),
184 | val view: @Composable () -> Unit
185 | )
186 |
187 | @Composable
188 | fun OperatorChip(operator: Operator) {
189 | var enabled by operator.enabled
190 | FilterChip(
191 | onClick = { enabled = !enabled },
192 | selected = enabled,
193 | label = { Text(operator.name) },
194 | elevation = null
195 | )
196 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------