├── .editorconfig
├── .gitattributes
├── .github
└── workflows
│ ├── build.yml
│ ├── code_style.yml
│ └── wiki.yml
├── .gitignore
├── .hooks
├── README.md
└── pre-commit
├── .run
└── desktopApp.run.xml
├── LICENSE.txt
├── README.md
├── build.gradle.kts
├── gradle.properties
├── gradle
├── libs.versions.toml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── ktor-boost
├── build.gradle.kts
└── src
│ ├── androidMain
│ ├── AndroidManifest.xml
│ └── kotlin
│ │ └── getPlatformName.kt
│ ├── commonMain
│ └── kotlin
│ │ ├── KtorDeferredResultExtension.kt
│ │ ├── KtorResultExtension.kt
│ │ ├── ResultExtensions.kt
│ │ ├── SampleLib.kt
│ │ └── SuspendRunCatching.kt
│ ├── commonTest
│ └── kotlin
│ │ ├── HttpClientDeferredExtensionsTest.kt
│ │ ├── HttpClientExtensionsTest.kt
│ │ └── RunCatchingTest.kt
│ ├── desktopMain
│ └── kotlin
│ │ └── getPlatformName.kt
│ └── iosMain
│ └── kotlin
│ └── getPlatformName.kt
├── sample
├── androidApp
│ ├── build.gradle.kts
│ └── src
│ │ └── androidMain
│ │ ├── AndroidManifest.xml
│ │ ├── kotlin
│ │ └── com
│ │ │ └── myapplication
│ │ │ └── MainActivity.kt
│ │ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ └── strings.xml
├── desktopApp
│ ├── build.gradle.kts
│ └── src
│ │ └── jvmMain
│ │ └── kotlin
│ │ └── main.kt
├── iosApp
│ ├── Configuration
│ │ └── Config.xcconfig
│ ├── iosApp.xcodeproj
│ │ └── project.pbxproj
│ └── iosApp
│ │ ├── Assets.xcassets
│ │ ├── AccentColor.colorset
│ │ │ └── Contents.json
│ │ ├── AppIcon.appiconset
│ │ │ ├── Contents.json
│ │ │ └── app-icon-1024.png
│ │ └── Contents.json
│ │ ├── ContentView.swift
│ │ ├── Info.plist
│ │ ├── Preview Content
│ │ └── Preview Assets.xcassets
│ │ │ └── Contents.json
│ │ └── iOSApp.swift
└── shared
│ ├── build.gradle.kts
│ └── src
│ ├── androidMain
│ ├── AndroidManifest.xml
│ └── kotlin
│ │ └── main.android.kt
│ ├── commonMain
│ ├── kotlin
│ │ └── App.kt
│ └── resources
│ │ └── compose-multiplatform.xml
│ ├── desktopMain
│ └── kotlin
│ │ └── main.desktop.kt
│ └── iosMain
│ └── kotlin
│ └── main.ios.kt
├── settings.gradle.kts
└── tools
└── ktlint
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*.{kt,kts}]
4 | ktlint_standard_filename = disabled
5 | ktlint_standard_no-wildcard-imports = disabled
6 | ktlint_standard_function-naming = disabled
7 | ktlint_function_naming_ignore_when_annotated_with=Composable
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | sample/** linguist-detectable
2 | sample/** -linguist-documentation
3 | sample/**/*.xml -linguist-detectable
4 | sample/**/*.plist -linguist-detectable
5 | *.kts linguist-language=Kotlin
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build Multiplatform project
2 | on:
3 | push:
4 | branches:
5 | - main
6 | - feature/ci_support
7 | pull_request:
8 |
9 | jobs:
10 | build-multiplatform-project:
11 | strategy:
12 | fail-fast: false
13 | matrix:
14 | os: [ubuntu-20.04, macos-12, windows-2022]
15 | gradle: [8.3]
16 | runs-on: ${{ matrix.os }}
17 | steps:
18 | - uses: actions/checkout@v3
19 | - uses: actions/setup-java@v3
20 | with:
21 | distribution: 'corretto'
22 | java-version: '17'
23 | - name: Build Multiplatform project
24 | shell: bash
25 | run: ./gradlew assemble
--------------------------------------------------------------------------------
/.github/workflows/code_style.yml:
--------------------------------------------------------------------------------
1 | name: Check code style
2 | on:
3 | push:
4 | branches:
5 | - main
6 | - feature/ci_support
7 | pull_request:
8 |
9 | jobs:
10 | check-code-style:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v3
14 | - uses: actions/setup-java@v3
15 | with:
16 | distribution: 'corretto'
17 | java-version: '17'
18 | - name: Check code style
19 | shell: bash
20 | run: ./gradlew ktlintCheck
--------------------------------------------------------------------------------
/.github/workflows/wiki.yml:
--------------------------------------------------------------------------------
1 | name: Publish Wiki
2 | on:
3 | push:
4 | branches:
5 | - main
6 | paths-ignore:
7 | - sample
8 |
9 | concurrency:
10 | group: publish-wiki
11 | cancel-in-progress: true
12 |
13 | jobs:
14 | publish-wiki:
15 | runs-on: ubuntu-latest
16 |
17 | permissions:
18 | contents: write
19 |
20 | steps:
21 | - name: Checkout repository
22 | uses: actions/checkout@v4
23 | with:
24 | submodules: 'recursive'
25 |
26 | - name: Setup Java
27 | uses: actions/setup-java@v3
28 | with:
29 | distribution: temurin
30 | java-version: 17
31 |
32 | - name: Setup Gradle
33 | uses: gradle/gradle-build-action@v2
34 |
35 | - name: Generate Wiki
36 | run: ./gradlew dokkaHtmlMultiModule
37 |
38 | - name: Upload Wiki
39 | uses: JamesIves/github-pages-deploy-action@v4
40 | with:
41 | folder: ./build/dokka/htmlMultiModule
42 | branch: gh-pages
43 | force: true
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | build/
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | sample/iosApp/Podfile.lock
11 | sample/iosApp/Pods/*
12 | sample/iosApp/iosApp.xcworkspace/*
13 | sample/iosApp/iosApp.xcodeproj/*
14 | !sample/iosApp/iosApp.xcodeproj/project.pbxproj
15 | shared/shared.podspec
16 |
17 | # Built application files
18 | *.apk
19 | *.ap_
20 |
21 | # Files for the ART/Dalvik VM
22 | *.dex
23 |
24 | # Java class files
25 | *.class
26 |
27 | # Generated files
28 | bin/
29 | gen/
30 | out/
31 |
32 |
33 | # Local configuration file (sdk path, etc)
34 | local.properties
35 |
36 | # Proguard folder generated by Eclipse
37 | proguard/
38 |
39 | # Log Files
40 | *.log
41 |
42 | # Android Studio Navigation editor temp files
43 | .navigation/
44 |
45 | # Android Studio captures folder
46 | captures/
47 |
48 | # Intellij
49 | .idea/workspace.xml
50 | .idea/tasks.xml
51 | .idea/gradle.xml
52 | .idea/dictionaries
53 | .idea/libraries
54 | app/.idea/
55 |
56 | # Mac
57 | *.DS_Store
58 |
59 | # Keystore files
60 | *.jks
61 |
62 | # Google Services (e.g. APIs or Firebase)
63 | google-services.json
64 |
65 | # Freeline
66 | freeline.py
67 | freeline/
68 | freeline_project_description.json
--------------------------------------------------------------------------------
/.hooks/README.md:
--------------------------------------------------------------------------------
1 | # Install Git Hooks
2 | `./gradlew setUpGitHooks`
3 |
--------------------------------------------------------------------------------
/.hooks/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # Auto format Kotlin files in the staging area
3 | CHANGED_FILES="$(git --no-pager diff --name-only --cached --diff-filter=ACMRTUXB --relative | grep '\.kt[s"]\?$')"
4 | if [ -z "$CHANGED_FILES" ]; then
5 | echo "No Kotlin staged files."
6 | else
7 | echo "Running ktlint format over these files:"
8 | echo "$CHANGED_FILES"
9 | if ! (echo "$CHANGED_FILES" | xargs ./tools/ktlint --format --relative); then
10 | exit $?
11 | else
12 | echo "Completed ktlint run."
13 | echo "$CHANGED_FILES" | while read -r file; do
14 | if [ -f "$file" ]; then
15 | git add "$file"
16 | fi
17 | done
18 | fi
19 | fi
20 |
--------------------------------------------------------------------------------
/.run/desktopApp.run.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | true
19 | true
20 | false
21 |
22 |
23 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 2020-2021 JetBrains s.r.o. and and respective authors and developers.
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 |
KtorBoost
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | 🚀 Simplifying Ktor for Easier Development.
25 | Ktor Boost streamlines HTTP requests in Ktor by offering functions that neatly package results in
26 | the Kotlin's Result class. It makes
27 | handling successes and errors clearer, simplifying error control in Ktor apps
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | ## Download
37 |
38 | [](https://search.maven.org/search?q=g:%22io.github.androidpoet%22%20AND%20a:%22ktor-boost%22)
39 |
40 | ### Without this line, you will receive an error response in the 'success' field.
41 |
42 | ```kotlin
43 | val client = HttpClient() {
44 | expectSuccess = true
45 | }
46 |
47 | ```
48 |
49 | ### Gradle
50 |
51 | Add the dependency below to your **module**'s `build.gradle` file:
52 |
53 | ```gradle
54 | sourceSets {
55 | val commonMain by getting {
56 | dependencies {
57 | implementation("io.github.androidpoet:ktor-boost:$version")
58 |
59 | }
60 | }
61 | }
62 | ```
63 |
64 | ## Usage
65 |
66 | ```kotlin
67 |
68 | // normal get,post,put...methods will be replaced by getResult,postResult,putResult...
69 |
70 | val result = httpClient.getResult("sample_get_url")
71 |
72 | val result = httpClient.postResult("sample_post_url")
73 |
74 | val result = httpClient.putResult("sample_put_url")
75 |
76 | val result = httpClient.deleteResult("sample_delete_url")
77 |
78 | val result = httpClient.patchResult("sample_patch_url")
79 |
80 | val result = httpClient.headResult("sample_head_url")
81 |
82 | val result = httpClient.optionsResult("sample_options_url")
83 |
84 |
85 | // for async and await methods use these
86 |
87 | val result = httpClient.getResultAsync("sample_get_url")
88 |
89 | val result = httpClient.postResultAsync("sample_post_url")
90 |
91 | val result = httpClient.putResultAsync("sample_put_url")
92 |
93 | val result = httpClient.deleteResultAsync("sample_delete_url")
94 |
95 | val result = httpClient.patchResultAsync("sample_patch_url")
96 |
97 | val result = httpClient.headResultAsync("sample_head_url")
98 |
99 | val result = httpClient.optionsResultAsync("sample_options_url")
100 |
101 |
102 | val deferredResult = httpClient.getResultAsync("sample_get_url")
103 | val result = deferredResult.await()
104 |
105 |
106 | ```
107 |
108 | ## Without KtorBoost
109 |
110 | Initially, when fetching data from APIs, the code directly gets the response's content, leading to
111 | repetitive use of the 'body()' method:
112 |
113 | ```kotlin
114 | // api service claas function
115 | suspend fun getUserNames(): List {
116 | return httpClient.get("trendingMovies").body()
117 | }
118 |
119 |
120 | //for async oprations
121 |
122 | suspend fun getAsyncUserNames(): Deferred> {
123 | return coroutineScope { async { httpClient.get("trendingMovies").body() } }
124 | }
125 |
126 |
127 |
128 | ```
129 |
130 | Handling errors involves enclosing each API call within separate try-catch blocks, causing code
131 | duplication:
132 |
133 | ```kotlin
134 | // viewModel
135 |
136 | viewModelScope.launch {
137 | try {
138 | val data = apiService.getUserNames()
139 | // handle data
140 | } catch (e: Throwable) {
141 | // handle error
142 | }
143 | }
144 |
145 | // Async Await
146 |
147 | viewModelScope.launch {
148 | try {
149 | val deferredData = apiService.getAsyncUserNames()
150 | deferredResult.await()
151 | // handle data
152 | } catch (e: Throwable) {
153 | // handle error
154 | }
155 | }
156 |
157 |
158 | ```
159 |
160 | ## With KtorBoost
161 |
162 | With improvements, the API calls are now focused solely on returning values:
163 |
164 | ```kotlin
165 | // api service claas function
166 | suspend fun getUserNamesResult() = httpClient.getResult>("trendingMovies")
167 |
168 |
169 | //for async oprations
170 |
171 | suspend fun getAsyncUserNames(): = httpClient.getResultAsync>("trendingMovies")
172 |
173 |
174 | ```
175 |
176 | This refined approach in error and response handling simplifies the code:
177 |
178 | ```kotlin
179 | // viewModel
180 |
181 | viewModelScope.launch {
182 | val result = apiService.getUserNames()
183 | result.onSuccess { data ->
184 | // handle data
185 | }.onFailure { error ->
186 | // handle error
187 | }
188 | }
189 |
190 |
191 | // Async Await
192 |
193 | viewModelScope.launch {
194 | val deferredResult = apiService.getAsyncUserNames()
195 | val result = deferredResult.await()
196 |
197 | result.onSuccess { data ->
198 | // handle data
199 | }.onFailure { error ->
200 | // handle error
201 | }
202 |
203 | }
204 |
205 | ```
206 |
207 | ## Different variations and use cases
208 |
209 | The solution offers multiple variations in response handling, enabling adaptability based on team
210 | preferences and project needs:
211 |
212 | ```kotlin
213 |
214 | //If you prefer executing the response function as a suspend function, useful for nested suspend
215 | //function usage on success or error:
216 |
217 | viewModelScope.launch {
218 | result.onSuccessSuspend { data ->
219 | // handle data
220 | }.onFailureSuspend { error ->
221 | // handle error
222 | }
223 | }
224 |
225 | ```
226 |
227 | ```kotlin
228 | // For cases solely interested in success response, using getOrNull() function and handling errors manually:
229 |
230 | viewModelScope.launch {
231 | if (result.isSuccess) {
232 | val data = result.getOrNull()
233 | // handle data
234 | } else {
235 | // handle error
236 | }
237 | }
238 |
239 | ```
240 |
241 | ```kotlin
242 |
243 |
244 | // Folding the response, a concise approach for clean and readable code:
245 |
246 | viewModelScope.launch {
247 | result.fold(onSuccess = { data ->
248 | // handle data
249 | }, onFailure = { error ->
250 | // handle error
251 | })
252 | }
253 |
254 | ```
255 |
256 | ```kotlin
257 |
258 |
259 | // Fold also supports suspend version:
260 |
261 | viewModelScope.launch {
262 | result.foldSuspend(
263 | onSuccess = { data ->
264 | // handle data
265 | }, onFailure = { error ->
266 | // handle error
267 | })
268 |
269 | }
270 |
271 | ```
272 |
273 | These diverse approaches in response handling empower you to select the most suitable method,
274 | whether for executing suspend functions,
275 | specifically handling success responses, or streamlining code for clearer readability.
276 |
277 | ## Find this repository useful? :heart:
278 |
279 | Support it by joining __[stargazers](https://github.com/androidpoet/KtorBoost/stargazers)__ for this
280 | repository. :star:
281 | Also, __[follow me](https://github.com/androidpoet)__ on GitHub for my next creations! 🤩
282 |
283 |
284 | # License
285 |
286 | ```xml
287 | Copyright 2023 AndroidPoet (Ranbir Singh)
288 |
289 | Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
290 |
291 | http://www.apache.org/licenses/LICENSE-2.0
292 |
293 | Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
294 | ```
295 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | // this is necessary to avoid the plugins to be loaded multiple times
3 | // in each subproject's classloader
4 | kotlin("multiplatform").apply(false)
5 | id("com.android.application").apply(false)
6 | id("com.android.library").apply(false)
7 | id("org.jetbrains.compose").apply(false)
8 | id("com.vanniktech.maven.publish").apply(false)
9 | id("org.jetbrains.dokka")
10 | id("org.jlleitschuh.gradle.ktlint")
11 | }
12 |
13 | subprojects {
14 | apply(plugin = "org.jlleitschuh.gradle.ktlint") // Version should be inherited from parent
15 |
16 | // Optionally configure plugin
17 | configure {
18 | version.set("1.0.1")
19 | }
20 | }
21 |
22 | tasks.register("setUpGitHooks") {
23 | group = "help"
24 | from("$rootDir/.hooks")
25 | into("$rootDir/.git/hooks")
26 | }
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Gradle
2 | org.gradle.jvmargs=-Xmx2048M -Dkotlin.daemon.jvm.options\="-Xmx2048M"
3 |
4 | #Kotlin
5 | kotlin.code.style=official
6 |
7 | #MPP
8 | kotlin.mpp.stability.nowarn=true
9 | kotlin.mpp.enableCInteropCommonization=true
10 | kotlin.mpp.androidSourceSetLayoutVersion=2
11 |
12 | #Compose
13 | org.jetbrains.compose.experimental.uikit.enabled=true
14 |
15 | #Android
16 | android.useAndroidX=true
17 | android.compileSdk=34
18 | android.targetSdk=34
19 | android.minSdk=21
20 |
21 | #Versions
22 | kotlin.version=1.9.10
23 | agp.version=8.1.1
24 | compose.version=1.5.3
25 | dokka.version=1.9.0
26 | klint.version=11.6.1
27 | maven-publish.version=0.25.3
28 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.0.2"
3 | kotlin = "1.9.0"
4 | nexus-publish = "2.0.0-rc-1"
5 | android-minSdk = "24"
6 | android-compileSdk = "33"
7 | ktor-client = "2.3.6"
8 | ktor-client-mock="2.3.6"
9 |
10 |
11 | [libraries]
12 | ktor-client = { module = "io.ktor:ktor-client-core", version.ref = "ktor-client" }
13 | ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor-client-mock" }
14 | kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
15 | ktor-desktop = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor-client" }
16 | [plugins]
17 | androidLibrary = { id = "com.android.library", version.ref = "agp" }
18 | kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
19 |
20 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Stop when "xargs" is not available.
209 | if ! command -v xargs >/dev/null 2>&1
210 | then
211 | die "xargs is not available"
212 | fi
213 |
214 | # Use "xargs" to parse quoted args.
215 | #
216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
217 | #
218 | # In Bash we could simply go:
219 | #
220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
221 | # set -- "${ARGS[@]}" "$@"
222 | #
223 | # but POSIX shell has neither arrays nor command substitution, so instead we
224 | # post-process each arg (as a line of input to sed) to backslash-escape any
225 | # character that might be a shell metacharacter, then use eval to reverse
226 | # that process (while maintaining the separation between arguments), and wrap
227 | # the whole thing up as a single "set" statement.
228 | #
229 | # This will of course break if any of these variables contains a newline or
230 | # an unmatched quote.
231 | #
232 |
233 | eval "set -- $(
234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
235 | xargs -n1 |
236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
237 | tr '\n' ' '
238 | )" '"$@"'
239 |
240 | exec "$JAVACMD" "$@"
241 |
--------------------------------------------------------------------------------
/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% equ 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% equ 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 | set EXIT_CODE=%ERRORLEVEL%
84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
86 | exit /b %EXIT_CODE%
87 |
88 | :mainEnd
89 | if "%OS%"=="Windows_NT" endlocal
90 |
91 | :omega
92 |
--------------------------------------------------------------------------------
/ktor-boost/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.vanniktech.maven.publish.SonatypeHost
2 |
3 | plugins {
4 | kotlin("multiplatform")
5 | id("com.android.library")
6 | id("org.jetbrains.dokka")
7 | id("com.vanniktech.maven.publish")
8 | }
9 |
10 | kotlin {
11 | androidTarget {
12 | publishLibraryVariants("release")
13 | }
14 | jvm("desktop")
15 |
16 | // jvm()
17 |
18 | listOf(
19 | iosX64(),
20 | iosArm64(),
21 | iosSimulatorArm64(),
22 | ).forEach { iosTarget ->
23 | iosTarget.binaries.framework {
24 | baseName = "ktor-boost"
25 | isStatic = true
26 | }
27 | }
28 |
29 | sourceSets {
30 | val commonMain by getting {
31 | dependencies {
32 | implementation(libs.ktor.client)
33 | }
34 | }
35 | val commonTest by getting {
36 | dependencies {
37 | implementation(libs.ktor.client.mock)
38 | implementation(libs.kotlin.test)
39 | }
40 | }
41 | val androidMain by getting {
42 | dependencies {
43 | }
44 | }
45 | val iosX64Main by getting
46 | val iosArm64Main by getting
47 | val iosSimulatorArm64Main by getting
48 | val iosMain by creating {
49 | dependsOn(commonMain)
50 | iosX64Main.dependsOn(this)
51 | iosArm64Main.dependsOn(this)
52 | iosSimulatorArm64Main.dependsOn(this)
53 | }
54 | val desktopMain by getting {
55 | dependencies {
56 | implementation(libs.ktor.desktop)
57 | }
58 | }
59 | }
60 | }
61 |
62 | android {
63 | compileSdk = (findProperty("android.compileSdk") as String).toInt()
64 | namespace = "com.androidpoet.ktor.boost"
65 |
66 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
67 | sourceSets["main"].res.srcDirs("src/androidMain/res")
68 | sourceSets["main"].resources.srcDirs("src/commonMain/resources")
69 |
70 | defaultConfig {
71 | minSdk = (findProperty("android.minSdk") as String).toInt()
72 | }
73 | compileOptions {
74 | sourceCompatibility = JavaVersion.VERSION_17
75 | targetCompatibility = JavaVersion.VERSION_17
76 | }
77 | kotlin {
78 | jvmToolchain(17)
79 | }
80 | }
81 |
82 | mavenPublishing {
83 | // publishToMavenCentral(SonatypeHost.DEFAULT)
84 | // or when publishing to https://s01.oss.sonatype.org
85 | publishToMavenCentral(SonatypeHost.S01, automaticRelease = true)
86 | signAllPublications()
87 | coordinates("io.github.androidpoet", "ktor-boost", "1.0.0")
88 |
89 | pom {
90 | name.set("ktor-boost")
91 | description.set("Simplifying Ktor for Easier Development.")
92 | inceptionYear.set("2023")
93 | url.set("https://github.com/AndroidPoet/KtorBoost/")
94 | licenses {
95 | license {
96 | name.set("The Apache License, Version 2.0")
97 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
98 | distribution.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
99 | }
100 | }
101 | developers {
102 | developer {
103 | id.set("ranbirk66")
104 | name.set("Ranbir Singh")
105 | url.set("https://github.com/androidpoet/")
106 | }
107 | }
108 | scm {
109 | url.set("https://github.com/AndroidPoet/KtorBoost/")
110 | connection.set("scm:git:git://github.com/AndroidPoet/KtorBoost.git")
111 | developerConnection.set("scm:git:ssh://github.com/AndroidPoet/KtorBoost.git")
112 | }
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/ktor-boost/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/ktor-boost/src/androidMain/kotlin/getPlatformName.kt:
--------------------------------------------------------------------------------
1 |
2 |
3 | actual fun getPlatformName(): String {
4 | return "Android"
5 | }
6 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonMain/kotlin/KtorDeferredResultExtension.kt:
--------------------------------------------------------------------------------
1 | import io.ktor.client.HttpClient
2 | import io.ktor.client.call.body
3 | import io.ktor.client.request.HttpRequestBuilder
4 | import io.ktor.client.request.delete
5 | import io.ktor.client.request.get
6 | import io.ktor.client.request.head
7 | import io.ktor.client.request.options
8 | import io.ktor.client.request.patch
9 | import io.ktor.client.request.post
10 | import io.ktor.client.request.put
11 | import kotlinx.coroutines.Deferred
12 | import kotlinx.coroutines.async
13 | import kotlinx.coroutines.coroutineScope
14 |
15 | /**
16 | * Executes an asynchronous HTTP GET request using the provided URL.
17 | *
18 | * @param urlString The URL for the GET request.
19 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
20 | * @return A Deferred> representing the asynchronous operation.
21 | */
22 | public suspend inline fun HttpClient.getResultAsync(
23 | urlString: String,
24 | noinline block: HttpRequestBuilder.() -> Unit = {},
25 | ): Deferred> =
26 | coroutineScope {
27 | async { runSafeSuspendCatching { get(urlString, block).body() } }
28 | }
29 |
30 | /**
31 | * Executes an asynchronous HTTP POST request using the provided URL.
32 | *
33 | * @param urlString The URL for the POST request.
34 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
35 | * @return A Deferred> representing the asynchronous operation.
36 | */
37 | public suspend inline fun HttpClient.postResultAsync(
38 | urlString: String,
39 | noinline block: HttpRequestBuilder.() -> Unit = {},
40 | ): Deferred> =
41 | coroutineScope {
42 | async { runSafeSuspendCatching { post(urlString, block).body() } }
43 | }
44 |
45 | /**
46 | * Executes an asynchronous HTTP PUT request using the provided URL.
47 | *
48 | * @param urlString The URL for the PUT request.
49 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
50 | * @return A Deferred> representing the asynchronous operation.
51 | */
52 | public suspend inline fun HttpClient.putResultAsync(
53 | urlString: String,
54 | noinline block: HttpRequestBuilder.() -> Unit = {},
55 | ): Deferred> =
56 | coroutineScope {
57 | async { runSafeSuspendCatching { put(urlString, block).body() } }
58 | }
59 |
60 | /**
61 | * Executes an asynchronous HTTP DELETE request using the provided URL.
62 | *
63 | * @param urlString The URL for the DELETE request.
64 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
65 | * @return A Deferred> representing the asynchronous operation.
66 | */
67 | public suspend inline fun HttpClient.deleteResultAsync(
68 | urlString: String,
69 | noinline block: HttpRequestBuilder.() -> Unit = {},
70 | ): Deferred> =
71 | coroutineScope {
72 | async { runSafeSuspendCatching { delete(urlString, block).body() } }
73 | }
74 |
75 | /**
76 | * Executes an asynchronous HTTP PATCH request using the provided URL.
77 | *
78 | * @param urlString The URL for the PATCH request.
79 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
80 | * @return A Deferred> representing the asynchronous operation.
81 | */
82 | public suspend inline fun HttpClient.patchResultAsync(
83 | urlString: String,
84 | noinline block: HttpRequestBuilder.() -> Unit = {},
85 | ): Deferred> =
86 | coroutineScope {
87 | async { runSafeSuspendCatching { patch(urlString, block).body() } }
88 | }
89 |
90 | /**
91 | * Executes an asynchronous HTTP HEAD request using the provided URL.
92 | *
93 | * @param urlString The URL for the HEAD request.
94 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
95 | * @return A Deferred> representing the asynchronous operation.
96 | */
97 | public suspend inline fun HttpClient.headResultAsync(
98 | urlString: String,
99 | noinline block: HttpRequestBuilder.() -> Unit = {},
100 | ): Deferred> =
101 | coroutineScope {
102 | async { runSafeSuspendCatching { head(urlString, block).body() } }
103 | }
104 |
105 | /**
106 | * Executes an asynchronous HTTP OPTIONS request using the provided URL.
107 | *
108 | * @param urlString The URL for the OPTIONS request.
109 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
110 | * @return A Deferred> representing the asynchronous operation.
111 | */
112 | public suspend inline fun HttpClient.optionsResultAsync(
113 | urlString: String,
114 | noinline block: HttpRequestBuilder.() -> Unit = {},
115 | ): Deferred> =
116 | coroutineScope {
117 | async { runSafeSuspendCatching { options(urlString, block).body() } }
118 | }
119 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonMain/kotlin/KtorResultExtension.kt:
--------------------------------------------------------------------------------
1 | import io.ktor.client.HttpClient
2 | import io.ktor.client.call.body
3 | import io.ktor.client.request.HttpRequestBuilder
4 | import io.ktor.client.request.delete
5 | import io.ktor.client.request.get
6 | import io.ktor.client.request.head
7 | import io.ktor.client.request.options
8 | import io.ktor.client.request.patch
9 | import io.ktor.client.request.post
10 | import io.ktor.client.request.put
11 |
12 | /**
13 | * Performs an HTTP GET request synchronously and returns the result as a [Result] of type [T].
14 | *
15 | * @param urlString The URL for the GET request.
16 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
17 | * @return Result representing the synchronous operation.
18 | */
19 | suspend inline fun HttpClient.getResult(
20 | urlString: String,
21 | noinline block: HttpRequestBuilder.() -> Unit = {},
22 | ): Result = runSafeSuspendCatching { get(urlString, block).body() }
23 |
24 | /**
25 | * Performs an HTTP POST request synchronously and returns the result as a [Result] of type [T].
26 | *
27 | * @param urlString The URL for the POST request.
28 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
29 | * @return Result representing the synchronous operation.
30 | */
31 | suspend inline fun HttpClient.postResult(
32 | urlString: String,
33 | noinline block: HttpRequestBuilder.() -> Unit = {},
34 | ): Result = runSafeSuspendCatching { post(urlString, block).body() }
35 |
36 | /**
37 | * Performs an HTTP PUT request synchronously and returns the result as a [Result] of type [T].
38 | *
39 | * @param urlString The URL for the PUT request.
40 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
41 | * @return Result representing the synchronous operation.
42 | */
43 | suspend inline fun HttpClient.putResult(
44 | urlString: String,
45 | noinline block: HttpRequestBuilder.() -> Unit = {},
46 | ): Result = runSafeSuspendCatching { put(urlString, block).body() }
47 |
48 | /**
49 | * Performs an HTTP DELETE request synchronously and returns the result as a [Result] of type [T].
50 | *
51 | * @param urlString The URL for the DELETE request.
52 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
53 | * @return Result representing the synchronous operation.
54 | */
55 | suspend inline fun HttpClient.deleteResult(
56 | urlString: String,
57 | noinline block: HttpRequestBuilder.() -> Unit = {},
58 | ): Result = runSafeSuspendCatching { delete(urlString, block).body() }
59 |
60 | /**
61 | * Performs an HTTP PATCH request synchronously and returns the result as a [Result] of type [T].
62 | *
63 | * @param urlString The URL for the PATCH request.
64 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
65 | * @return Result representing the synchronous operation.
66 | */
67 | suspend inline fun HttpClient.patchResult(
68 | urlString: String,
69 | noinline block: HttpRequestBuilder.() -> Unit = {},
70 | ): Result = runSafeSuspendCatching { patch(urlString, block).body() }
71 |
72 | /**
73 | * Performs an HTTP HEAD request synchronously and returns the result as a [Result] of type [T].
74 | *
75 | * @param urlString The URL for the HEAD request.
76 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
77 | * @return Result representing the synchronous operation.
78 | */
79 | suspend inline fun HttpClient.headResult(
80 | urlString: String,
81 | noinline block: HttpRequestBuilder.() -> Unit = {},
82 | ): Result = runSafeSuspendCatching { head(urlString, block).body() }
83 |
84 | /**
85 | * Performs an HTTP OPTIONS request synchronously and returns the result as a [Result] of type [T].
86 | *
87 | * @param urlString The URL for the OPTIONS request.
88 | * @param block Optional, allows customization of the request using HttpRequestBuilder.
89 | * @return Result representing the synchronous operation.
90 | */
91 | suspend inline fun HttpClient.optionsResult(
92 | urlString: String,
93 | noinline block: HttpRequestBuilder.() -> Unit = {},
94 | ): Result = runSafeSuspendCatching { options(urlString, block).body() }
95 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonMain/kotlin/ResultExtensions.kt:
--------------------------------------------------------------------------------
1 | import kotlin.contracts.ExperimentalContracts
2 | import kotlin.contracts.InvocationKind
3 | import kotlin.contracts.contract
4 |
5 | // https://github.com/skydoves/retrofit-adapters/blob/main/retrofit-adapters-result/src/main/kotlin/com/skydoves/retrofit/adapters/result/ResultExtensions.kt
6 |
7 | /**
8 | * Executes a suspend function [block] within a try-catch and returns the result as a [Result].
9 | *
10 | * @param block A suspend function that returns a result.
11 | * @return Result representing the success or failure of the provided suspend function.
12 | */
13 | public suspend inline fun runCatchingSuspend(crossinline block: suspend () -> R): Result {
14 | return try {
15 | Result.success(block())
16 | } catch (e: Throwable) {
17 | Result.failure(e)
18 | }
19 | }
20 |
21 | /**
22 | * Executes a suspend function [block] on the receiver [T] within a try-catch and returns the result as a [Result].
23 | *
24 | * @param block A suspend function that returns a result, acting on the receiver [T].
25 | * @return Result representing the success or failure of the provided suspend function.
26 | */
27 | public suspend inline fun T.runCatchingSuspend(crossinline block: suspend T.() -> R): Result {
28 | return try {
29 | Result.success(block())
30 | } catch (e: Throwable) {
31 | Result.failure(e)
32 | }
33 | }
34 |
35 | /**
36 | * Executes a suspend function [action] if the current result is a success.
37 | *
38 | * @param action A suspend function to be executed if the result is a success.
39 | * @return The current Result instance.
40 | */
41 | @OptIn(ExperimentalContracts::class)
42 | public suspend inline fun Result.onSuccessSuspend(crossinline action: suspend (value: T) -> Unit): Result {
43 | contract {
44 | callsInPlace(action, InvocationKind.AT_MOST_ONCE)
45 | }
46 | if (isSuccess) action(getOrThrow())
47 | return this
48 | }
49 |
50 | /**
51 | * Executes a suspend function [action] if the current result is a failure.
52 | *
53 | * @param action A suspend function to be executed if the result is a failure.
54 | * @return The current Result instance.
55 | */
56 | @OptIn(ExperimentalContracts::class)
57 | public suspend inline fun Result.onFailureSuspend(crossinline action: suspend (exception: Throwable) -> Unit): Result {
58 | contract {
59 | callsInPlace(action, InvocationKind.AT_MOST_ONCE)
60 | }
61 | exceptionOrNull()?.let { action(it) }
62 | return this
63 | }
64 |
65 | /**
66 | * Performs a fold operation on the Result, executing [onSuccess] if the Result is a success,
67 | * or [onFailure] if the Result is a failure.
68 | *
69 | * @param onSuccess A suspend function to be executed on success.
70 | * @param onFailure A suspend function to be executed on failure.
71 | * @return Result of applying the corresponding function based on the current Result state.
72 | */
73 | @OptIn(ExperimentalContracts::class)
74 | public suspend inline fun Result.foldSuspend(
75 | crossinline onSuccess: suspend (value: T) -> R,
76 | crossinline onFailure: suspend (exception: Throwable) -> R,
77 | ): R {
78 | contract {
79 | callsInPlace(onSuccess, InvocationKind.AT_MOST_ONCE)
80 | callsInPlace(onFailure, InvocationKind.AT_MOST_ONCE)
81 | }
82 | return when (val exception = exceptionOrNull()) {
83 | null -> onSuccess(getOrThrow())
84 | else -> onFailure(exception)
85 | }
86 | }
87 |
88 | /**
89 | * Performs a mapping operation on the Result, transforming the value if the Result is a success.
90 | *
91 | * @param transform A suspend function to transform the value on success.
92 | * @return Result representing the transformed value or failure based on the current Result state.
93 | */
94 | @OptIn(ExperimentalContracts::class)
95 | public suspend inline fun Result.mapSuspend(crossinline transform: suspend (value: T) -> R): Result {
96 | contract {
97 | callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
98 | }
99 | return when {
100 | isSuccess -> Result.success(transform(getOrThrow()))
101 | else -> Result.failure(exceptionOrNull()!!)
102 | }
103 | }
104 |
105 | /**
106 | * Recovers from a failure by executing [transform] to create a new value if the Result is a failure.
107 | *
108 | * @param transform A suspend function to transform the exception on failure.
109 | * @return Result representing the recovered value or original success based on the current Result state.
110 | */
111 | @OptIn(ExperimentalContracts::class)
112 | public suspend inline fun Result.recoverSuspend(crossinline transform: suspend (exception: Throwable) -> R): Result {
113 | contract {
114 | callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
115 | }
116 | return when (val exception = exceptionOrNull()) {
117 | null -> this
118 | else -> Result.success(transform(exception))
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonMain/kotlin/SampleLib.kt:
--------------------------------------------------------------------------------
1 | expect fun getPlatformName(): String
2 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonMain/kotlin/SuspendRunCatching.kt:
--------------------------------------------------------------------------------
1 | import io.ktor.client.plugins.ResponseException
2 | import kotlin.coroutines.cancellation.CancellationException
3 |
4 | /**
5 | * Runs a suspending function [block] safely, catching any exceptions that occur during its execution.
6 | * Returns a [Result] indicating success or failure of the function.
7 | *
8 | * @param block the suspending function to be executed safely
9 | * @return a [Result] indicating success ([Result.success]) or failure ([Result.failure]) of the function
10 | * @throws CancellationException if the coroutine is cancelled during the execution of [block]
11 | */
12 | public suspend inline fun runSafeSuspendCatching(block: () -> R): Result {
13 | return try {
14 | Result.success(block())
15 | } catch (c: CancellationException) {
16 | throw c
17 | } catch (e: ResponseException) {
18 | Result.failure(e)
19 | } catch (t: Throwable) {
20 | Result.failure(t)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonTest/kotlin/HttpClientDeferredExtensionsTest.kt:
--------------------------------------------------------------------------------
1 | import io.ktor.client.HttpClient
2 | import io.ktor.client.engine.mock.MockEngine
3 | import io.ktor.client.engine.mock.respondError
4 | import io.ktor.http.HttpMethod
5 | import io.ktor.http.HttpStatusCode
6 | import kotlinx.coroutines.runBlocking
7 | import kotlin.test.Test
8 | import kotlin.test.assertEquals
9 | import kotlin.test.assertNotNull
10 | import kotlin.test.assertTrue
11 |
12 | class HttpClientDeferredExtensionsTest {
13 | private val mockEngine =
14 | MockEngine { request ->
15 | val responseContent =
16 | when (request.method) {
17 | HttpMethod.Get -> "get success"
18 | HttpMethod.Post -> "post success"
19 | HttpMethod.Put -> "put success"
20 | HttpMethod.Delete -> "delete success"
21 | HttpMethod.Patch -> "patch success"
22 | HttpMethod.Head -> "head success"
23 | HttpMethod.Options -> "options success"
24 | else -> "" // Handle other methods if needed
25 | }
26 | respondError(HttpStatusCode.Conflict, content = responseContent)
27 | }
28 |
29 | private val httpClient = HttpClient(mockEngine)
30 |
31 | @Test
32 | fun `test getDeferredResult extension function`() {
33 | runBlocking {
34 | val deferredResult = httpClient.getResultAsync("sample_get_url")
35 | val result = deferredResult.await()
36 | assertTrue(result.isSuccess)
37 |
38 | var onSuccessCalled = true
39 | result.onSuccess {
40 | onSuccessCalled = false
41 | }
42 | assertEquals(expected = true, actual = onSuccessCalled)
43 | result.onFailure {
44 | // assertNotNull(it)
45 | }
46 |
47 | // val responseBody = result.getOrThrow()
48 | // assertNotNull(responseBody)
49 | // assertEquals("get success", responseBody)
50 | }
51 | }
52 |
53 | @Test
54 | fun `test postDeferredResult extension function`() {
55 | runBlocking {
56 | val deferredResult = httpClient.postResultAsync("sample_post_url")
57 | val result = deferredResult.await()
58 | assertTrue(result.isSuccess)
59 | val responseBody = result.getOrNull()
60 | assertNotNull(responseBody)
61 | assertEquals("post success", responseBody)
62 | }
63 | }
64 |
65 | @Test
66 | fun `test putDeferredResult extension function`() {
67 | runBlocking {
68 | val deferredResult = httpClient.putResultAsync("sample_put_url")
69 | val result = deferredResult.await()
70 | assertTrue(result.isSuccess)
71 | val responseBody = result.getOrNull()
72 | assertNotNull(responseBody)
73 | assertEquals("put success", responseBody)
74 | }
75 | }
76 |
77 | @Test
78 | fun `test deleteDeferredResult extension function`() {
79 | runBlocking {
80 | val deferredResult = httpClient.deleteResultAsync("sample_delete_url")
81 | val result = deferredResult.await()
82 | assertTrue(result.isSuccess)
83 | val responseBody = result.getOrNull()
84 | assertNotNull(responseBody)
85 | assertEquals("delete success", responseBody)
86 | }
87 | }
88 |
89 | @Test
90 | fun `test patchDeferredResult extension function`() {
91 | runBlocking {
92 | val deferredResult = httpClient.patchResultAsync("sample_patch_url")
93 | val result = deferredResult.await()
94 | assertTrue(result.isSuccess)
95 | val responseBody = result.getOrNull()
96 | assertNotNull(responseBody)
97 | assertEquals("patch success", responseBody)
98 | }
99 | }
100 |
101 | @Test
102 | fun `test headDeferredResult extension function`() {
103 | runBlocking {
104 | val deferredResult = httpClient.headResultAsync("sample_head_url")
105 | val result = deferredResult.await()
106 | assertTrue(result.isSuccess)
107 | val responseBody = result.getOrNull()
108 | assertNotNull(responseBody)
109 | assertEquals("head success", responseBody)
110 | }
111 | }
112 |
113 | @Test
114 | fun `test optionsDeferredResult extension function`() {
115 | runBlocking {
116 | val deferredResult = httpClient.optionsResultAsync("sample_options_url")
117 | val result = deferredResult.await()
118 | assertTrue(result.isSuccess)
119 | val responseBody = result.getOrNull()
120 | assertNotNull(responseBody)
121 | assertEquals("options success", responseBody)
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonTest/kotlin/HttpClientExtensionsTest.kt:
--------------------------------------------------------------------------------
1 | import io.ktor.client.HttpClient
2 | import io.ktor.client.engine.mock.MockEngine
3 | import io.ktor.client.engine.mock.respondError
4 | import io.ktor.http.HttpMethod
5 | import io.ktor.http.HttpStatusCode
6 | import kotlinx.coroutines.runBlocking
7 | import kotlin.test.Test
8 | import kotlin.test.assertEquals
9 | import kotlin.test.assertNotNull
10 | import kotlin.test.assertTrue
11 |
12 | class HttpClientExtensionsTest {
13 | private val mockEngine =
14 | MockEngine { request ->
15 | val responseContent =
16 | when (request.method) {
17 | HttpMethod.Get -> "get success"
18 | HttpMethod.Post -> "post success"
19 | HttpMethod.Put -> "put success"
20 | HttpMethod.Delete -> "delete success"
21 | HttpMethod.Patch -> "patch success"
22 | HttpMethod.Head -> "head success"
23 | HttpMethod.Options -> "options success"
24 | else -> "" // Handle other methods if needed
25 | }
26 | respondError(HttpStatusCode.BadGateway, content = responseContent)
27 | }
28 |
29 | private val httpClient = HttpClient(mockEngine)
30 |
31 | @Test
32 | fun `test getResult extension function`() {
33 | runBlocking {
34 | val result = httpClient.getResult("sample_get_url")
35 |
36 | assertTrue(result.isSuccess)
37 | val responseBody = result.getOrNull()
38 | assertNotNull(responseBody)
39 | assertEquals("get success", responseBody)
40 | }
41 | }
42 |
43 | @Test
44 | fun `test postResult extension function`() {
45 | runBlocking {
46 | val result = httpClient.postResult("sample_post_url")
47 | assertTrue(result.isSuccess)
48 | val responseBody = result.getOrNull()
49 | assertNotNull(responseBody)
50 | assertEquals("post success", responseBody)
51 | }
52 | }
53 |
54 | @Test
55 | fun `test putResult extension function`() {
56 | runBlocking {
57 | val result = httpClient.putResult("sample_put_url")
58 |
59 | assertTrue(result.isSuccess)
60 | val responseBody = result.getOrNull()
61 | assertNotNull(responseBody)
62 | assertEquals("put success", responseBody)
63 | }
64 | }
65 |
66 | @Test
67 | fun `test deleteResult extension function`() {
68 | runBlocking {
69 | val result = httpClient.deleteResult("sample_delete_url")
70 |
71 | assertTrue(result.isSuccess)
72 | val responseBody = result.getOrNull()
73 | assertNotNull(responseBody)
74 | assertEquals("delete success", responseBody)
75 | }
76 | }
77 |
78 | @Test
79 | fun `test patchResult extension function`() {
80 | runBlocking {
81 | val result = httpClient.patchResult("sample_patch_url")
82 |
83 | assertTrue(result.isSuccess)
84 | val responseBody = result.getOrNull()
85 | assertNotNull(responseBody)
86 | assertEquals("patch success", responseBody)
87 | }
88 | }
89 |
90 | @Test
91 | fun `test headResult extension function`() {
92 | runBlocking {
93 | val result = httpClient.headResult("sample_head_url")
94 | assertTrue(result.isSuccess)
95 | val responseBody = result.getOrNull()
96 | assertNotNull(responseBody)
97 | assertEquals("head success", responseBody)
98 | }
99 | }
100 |
101 | @Test
102 | fun `test optionsResult extension function`() {
103 | runBlocking {
104 | val result = httpClient.optionsResult("sample_options_url")
105 |
106 | assertTrue(result.isSuccess)
107 | val responseBody = result.getOrNull()
108 | assertNotNull(responseBody)
109 | assertEquals("options success", responseBody)
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/ktor-boost/src/commonTest/kotlin/RunCatchingTest.kt:
--------------------------------------------------------------------------------
1 | import kotlinx.coroutines.CancellationException
2 | import kotlinx.coroutines.runBlocking
3 | import kotlin.test.Test
4 | import kotlin.test.assertEquals
5 | import kotlin.test.assertTrue
6 | import kotlin.test.fail
7 |
8 | class RunCatchingTest {
9 | @Test
10 | fun `test runSafeSuspendCatching extension function CancellationException`() {
11 | runBlocking {
12 | try {
13 | runSafeSuspendCatching {
14 | throw CancellationException("Simulated cancellation")
15 | }.onFailure {
16 | fail("Caught an CancellationException")
17 | }
18 | // Fail the test if no exception is thrown
19 | fail("Expected CancellationException, but no exception was thrown.")
20 | } catch (exception: CancellationException) {
21 | assertEquals("Simulated cancellation", exception.message)
22 |
23 | // Add any other necessary assertions or handling for the rethrown exception
24 | } catch (e: Throwable) {
25 | // Fail the test if an unexpected exception is caught
26 | fail("Caught an unexpected exception: ${e.message}")
27 | }
28 | }
29 | }
30 |
31 | @Test
32 | fun `test runCatching extension function CancellationException`() {
33 | runBlocking {
34 | runCatching {
35 | throw CancellationException("Simulated cancellation")
36 | }.onSuccess {
37 | // Handle success if needed (not relevant in this scenario)
38 | // Fail the test explicitly if it reaches here unexpectedly
39 | fail("Expected onFailure to be called, but onSuccess was invoked.")
40 | }.onFailure { exception ->
41 | assertTrue(exception is CancellationException)
42 | assertEquals("Simulated cancellation", exception.message)
43 | // Add any other necessary assertions or handling for the failure
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/ktor-boost/src/desktopMain/kotlin/getPlatformName.kt:
--------------------------------------------------------------------------------
1 |
2 |
3 | actual fun getPlatformName(): String {
4 | return "Desktop"
5 | }
6 |
--------------------------------------------------------------------------------
/ktor-boost/src/iosMain/kotlin/getPlatformName.kt:
--------------------------------------------------------------------------------
1 |
2 |
3 | actual fun getPlatformName(): String {
4 | return "iOS"
5 | }
6 |
--------------------------------------------------------------------------------
/sample/androidApp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("multiplatform")
3 | id("com.android.application")
4 | id("org.jetbrains.compose")
5 | }
6 |
7 | kotlin {
8 | androidTarget()
9 | sourceSets {
10 | val androidMain by getting {
11 | dependencies {
12 | implementation(project(":sample:shared"))
13 | }
14 | }
15 | }
16 | }
17 |
18 | android {
19 | compileSdk = (findProperty("android.compileSdk") as String).toInt()
20 | namespace = "com.myapplication"
21 |
22 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
23 |
24 | defaultConfig {
25 | applicationId = "com.myapplication.MyApplication"
26 | minSdk = (findProperty("android.minSdk") as String).toInt()
27 | targetSdk = (findProperty("android.targetSdk") as String).toInt()
28 | versionCode = 1
29 | versionName = "1.0"
30 | }
31 | compileOptions {
32 | sourceCompatibility = JavaVersion.VERSION_17
33 | targetCompatibility = JavaVersion.VERSION_17
34 | }
35 | kotlin {
36 | jvmToolchain(17)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/kotlin/com/myapplication/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.myapplication
2 |
3 | import MainView
4 | import android.os.Bundle
5 | import androidx.activity.compose.setContent
6 | import androidx.appcompat.app.AppCompatActivity
7 |
8 | class MainActivity : AppCompatActivity() {
9 | override fun onCreate(savedInstanceState: Bundle?) {
10 | super.onCreate(savedInstanceState)
11 |
12 | setContent {
13 | MainView()
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/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 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/androidApp/src/androidMain/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/sample/androidApp/src/androidMain/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | My application
3 |
--------------------------------------------------------------------------------
/sample/desktopApp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.compose.desktop.application.dsl.TargetFormat
2 |
3 | plugins {
4 | kotlin("multiplatform")
5 | id("org.jetbrains.compose")
6 | }
7 |
8 | kotlin {
9 | jvm()
10 | sourceSets {
11 | val jvmMain by getting {
12 | dependencies {
13 | implementation(compose.desktop.currentOs)
14 | implementation(project(":sample:shared"))
15 | }
16 | }
17 | }
18 | }
19 |
20 | compose.desktop {
21 | application {
22 | mainClass = "MainKt"
23 |
24 | nativeDistributions {
25 | targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
26 | packageName = "KotlinMultiplatformComposeDesktopApplication"
27 | packageVersion = "1.0.0"
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/sample/desktopApp/src/jvmMain/kotlin/main.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.window.Window
2 | import androidx.compose.ui.window.application
3 |
4 | fun main() =
5 | application {
6 | Window(onCloseRequest = ::exitApplication) {
7 | MainView()
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/sample/iosApp/Configuration/Config.xcconfig:
--------------------------------------------------------------------------------
1 | TEAM_ID=
2 | BUNDLE_ID=com.myapplication.MyApplication
3 | APP_NAME=My application
4 |
--------------------------------------------------------------------------------
/sample/iosApp/iosApp.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 50;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 058557BB273AAA24004C7B11 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 058557BA273AAA24004C7B11 /* Assets.xcassets */; };
11 | 058557D9273AAEEB004C7B11 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 058557D8273AAEEB004C7B11 /* Preview Assets.xcassets */; };
12 | 2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2152FB032600AC8F00CF470E /* iOSApp.swift */; };
13 | 7555FF83242A565900829871 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7555FF82242A565900829871 /* ContentView.swift */; };
14 | /* End PBXBuildFile section */
15 |
16 | /* Begin PBXFileReference section */
17 | 058557BA273AAA24004C7B11 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
18 | 058557D8273AAEEB004C7B11 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; };
19 | 2152FB032600AC8F00CF470E /* iOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iOSApp.swift; sourceTree = ""; };
20 | 7555FF7B242A565900829871 /* My application.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "My application.app"; sourceTree = BUILT_PRODUCTS_DIR; };
21 | 7555FF82242A565900829871 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; };
22 | 7555FF8C242A565B00829871 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
23 | AB3632DC29227652001CCB65 /* Config.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = ""; };
24 | /* End PBXFileReference section */
25 |
26 | /* Begin PBXFrameworksBuildPhase section */
27 | F85CB1118929364A9C6EFABC /* Frameworks */ = {
28 | isa = PBXFrameworksBuildPhase;
29 | buildActionMask = 2147483647;
30 | files = (
31 | );
32 | runOnlyForDeploymentPostprocessing = 0;
33 | };
34 | /* End PBXFrameworksBuildPhase section */
35 |
36 | /* Begin PBXGroup section */
37 | 058557D7273AAEEB004C7B11 /* Preview Content */ = {
38 | isa = PBXGroup;
39 | children = (
40 | 058557D8273AAEEB004C7B11 /* Preview Assets.xcassets */,
41 | );
42 | path = "Preview Content";
43 | sourceTree = "";
44 | };
45 | 42799AB246E5F90AF97AA0EF /* Frameworks */ = {
46 | isa = PBXGroup;
47 | children = (
48 | );
49 | name = Frameworks;
50 | sourceTree = "";
51 | };
52 | 7555FF72242A565900829871 = {
53 | isa = PBXGroup;
54 | children = (
55 | AB1DB47929225F7C00F7AF9C /* Configuration */,
56 | 7555FF7D242A565900829871 /* iosApp */,
57 | 7555FF7C242A565900829871 /* Products */,
58 | 42799AB246E5F90AF97AA0EF /* Frameworks */,
59 | );
60 | sourceTree = "";
61 | };
62 | 7555FF7C242A565900829871 /* Products */ = {
63 | isa = PBXGroup;
64 | children = (
65 | 7555FF7B242A565900829871 /* My application.app */,
66 | );
67 | name = Products;
68 | sourceTree = "";
69 | };
70 | 7555FF7D242A565900829871 /* iosApp */ = {
71 | isa = PBXGroup;
72 | children = (
73 | 058557BA273AAA24004C7B11 /* Assets.xcassets */,
74 | 7555FF82242A565900829871 /* ContentView.swift */,
75 | 7555FF8C242A565B00829871 /* Info.plist */,
76 | 2152FB032600AC8F00CF470E /* iOSApp.swift */,
77 | 058557D7273AAEEB004C7B11 /* Preview Content */,
78 | );
79 | path = iosApp;
80 | sourceTree = "";
81 | };
82 | AB1DB47929225F7C00F7AF9C /* Configuration */ = {
83 | isa = PBXGroup;
84 | children = (
85 | AB3632DC29227652001CCB65 /* Config.xcconfig */,
86 | );
87 | path = Configuration;
88 | sourceTree = "";
89 | };
90 | /* End PBXGroup section */
91 |
92 | /* Begin PBXNativeTarget section */
93 | 7555FF7A242A565900829871 /* iosApp */ = {
94 | isa = PBXNativeTarget;
95 | buildConfigurationList = 7555FFA5242A565B00829871 /* Build configuration list for PBXNativeTarget "iosApp" */;
96 | buildPhases = (
97 | 05D91A922A5F233C00F138EB /* Compile Kotlin */,
98 | 7555FF77242A565900829871 /* Sources */,
99 | 7555FF79242A565900829871 /* Resources */,
100 | F85CB1118929364A9C6EFABC /* Frameworks */,
101 | );
102 | buildRules = (
103 | );
104 | dependencies = (
105 | );
106 | name = iosApp;
107 | productName = iosApp;
108 | productReference = 7555FF7B242A565900829871 /* My application.app */;
109 | productType = "com.apple.product-type.application";
110 | };
111 | /* End PBXNativeTarget section */
112 |
113 | /* Begin PBXProject section */
114 | 7555FF73242A565900829871 /* Project object */ = {
115 | isa = PBXProject;
116 | attributes = {
117 | LastSwiftUpdateCheck = 1130;
118 | LastUpgradeCheck = 1130;
119 | ORGANIZATIONNAME = orgName;
120 | TargetAttributes = {
121 | 7555FF7A242A565900829871 = {
122 | CreatedOnToolsVersion = 11.3.1;
123 | };
124 | };
125 | };
126 | buildConfigurationList = 7555FF76242A565900829871 /* Build configuration list for PBXProject "iosApp" */;
127 | compatibilityVersion = "Xcode 9.3";
128 | developmentRegion = en;
129 | hasScannedForEncodings = 0;
130 | knownRegions = (
131 | en,
132 | Base,
133 | );
134 | mainGroup = 7555FF72242A565900829871;
135 | productRefGroup = 7555FF7C242A565900829871 /* Products */;
136 | projectDirPath = "";
137 | projectRoot = "";
138 | targets = (
139 | 7555FF7A242A565900829871 /* iosApp */,
140 | );
141 | };
142 | /* End PBXProject section */
143 |
144 | /* Begin PBXResourcesBuildPhase section */
145 | 7555FF79242A565900829871 /* Resources */ = {
146 | isa = PBXResourcesBuildPhase;
147 | buildActionMask = 2147483647;
148 | files = (
149 | 058557D9273AAEEB004C7B11 /* Preview Assets.xcassets in Resources */,
150 | 058557BB273AAA24004C7B11 /* Assets.xcassets in Resources */,
151 | );
152 | runOnlyForDeploymentPostprocessing = 0;
153 | };
154 | /* End PBXResourcesBuildPhase section */
155 |
156 | /* Begin PBXShellScriptBuildPhase section */
157 | 05D91A922A5F233C00F138EB /* Compile Kotlin */ = {
158 | isa = PBXShellScriptBuildPhase;
159 | buildActionMask = 2147483647;
160 | files = (
161 | );
162 | inputFileListPaths = (
163 | );
164 | inputPaths = (
165 | );
166 | name = "Compile Kotlin";
167 | outputFileListPaths = (
168 | );
169 | outputPaths = (
170 | );
171 | runOnlyForDeploymentPostprocessing = 0;
172 | shellPath = /bin/sh;
173 | shellScript = "cd \"$SRCROOT/../..\"\n./gradlew :sample:shared:embedAndSignAppleFrameworkForXcode";
174 | };
175 | /* End PBXShellScriptBuildPhase section */
176 |
177 | /* Begin PBXSourcesBuildPhase section */
178 | 7555FF77242A565900829871 /* Sources */ = {
179 | isa = PBXSourcesBuildPhase;
180 | buildActionMask = 2147483647;
181 | files = (
182 | 2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */,
183 | 7555FF83242A565900829871 /* ContentView.swift in Sources */,
184 | );
185 | runOnlyForDeploymentPostprocessing = 0;
186 | };
187 | /* End PBXSourcesBuildPhase section */
188 |
189 | /* Begin XCBuildConfiguration section */
190 | 7555FFA3242A565B00829871 /* Debug */ = {
191 | isa = XCBuildConfiguration;
192 | baseConfigurationReference = AB3632DC29227652001CCB65 /* Config.xcconfig */;
193 | buildSettings = {
194 | ALWAYS_SEARCH_USER_PATHS = NO;
195 | CLANG_ANALYZER_NONNULL = YES;
196 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
197 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
198 | CLANG_CXX_LIBRARY = "libc++";
199 | CLANG_ENABLE_MODULES = YES;
200 | CLANG_ENABLE_OBJC_ARC = YES;
201 | CLANG_ENABLE_OBJC_WEAK = YES;
202 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
203 | CLANG_WARN_BOOL_CONVERSION = YES;
204 | CLANG_WARN_COMMA = YES;
205 | CLANG_WARN_CONSTANT_CONVERSION = YES;
206 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
207 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
208 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
209 | CLANG_WARN_EMPTY_BODY = YES;
210 | CLANG_WARN_ENUM_CONVERSION = YES;
211 | CLANG_WARN_INFINITE_RECURSION = YES;
212 | CLANG_WARN_INT_CONVERSION = YES;
213 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
214 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
215 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
216 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
217 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
218 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
219 | CLANG_WARN_STRICT_PROTOTYPES = YES;
220 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
221 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
222 | CLANG_WARN_UNREACHABLE_CODE = YES;
223 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
224 | COPY_PHASE_STRIP = NO;
225 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
226 | ENABLE_STRICT_OBJC_MSGSEND = YES;
227 | ENABLE_TESTABILITY = YES;
228 | GCC_C_LANGUAGE_STANDARD = gnu11;
229 | GCC_DYNAMIC_NO_PIC = NO;
230 | GCC_NO_COMMON_BLOCKS = YES;
231 | GCC_OPTIMIZATION_LEVEL = 0;
232 | GCC_PREPROCESSOR_DEFINITIONS = (
233 | "DEBUG=1",
234 | "$(inherited)",
235 | );
236 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
237 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
238 | GCC_WARN_UNDECLARED_SELECTOR = YES;
239 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
240 | GCC_WARN_UNUSED_FUNCTION = YES;
241 | GCC_WARN_UNUSED_VARIABLE = YES;
242 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
243 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
244 | MTL_FAST_MATH = YES;
245 | ONLY_ACTIVE_ARCH = YES;
246 | SDKROOT = iphoneos;
247 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
248 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
249 | };
250 | name = Debug;
251 | };
252 | 7555FFA4242A565B00829871 /* Release */ = {
253 | isa = XCBuildConfiguration;
254 | baseConfigurationReference = AB3632DC29227652001CCB65 /* Config.xcconfig */;
255 | buildSettings = {
256 | ALWAYS_SEARCH_USER_PATHS = NO;
257 | CLANG_ANALYZER_NONNULL = YES;
258 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
259 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
260 | CLANG_CXX_LIBRARY = "libc++";
261 | CLANG_ENABLE_MODULES = YES;
262 | CLANG_ENABLE_OBJC_ARC = YES;
263 | CLANG_ENABLE_OBJC_WEAK = YES;
264 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
265 | CLANG_WARN_BOOL_CONVERSION = YES;
266 | CLANG_WARN_COMMA = YES;
267 | CLANG_WARN_CONSTANT_CONVERSION = YES;
268 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
269 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
270 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
271 | CLANG_WARN_EMPTY_BODY = YES;
272 | CLANG_WARN_ENUM_CONVERSION = YES;
273 | CLANG_WARN_INFINITE_RECURSION = YES;
274 | CLANG_WARN_INT_CONVERSION = YES;
275 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
276 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
277 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
278 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
279 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
280 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
281 | CLANG_WARN_STRICT_PROTOTYPES = YES;
282 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
283 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
284 | CLANG_WARN_UNREACHABLE_CODE = YES;
285 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
286 | COPY_PHASE_STRIP = NO;
287 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
288 | ENABLE_NS_ASSERTIONS = NO;
289 | ENABLE_STRICT_OBJC_MSGSEND = YES;
290 | GCC_C_LANGUAGE_STANDARD = gnu11;
291 | GCC_NO_COMMON_BLOCKS = YES;
292 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
293 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
294 | GCC_WARN_UNDECLARED_SELECTOR = YES;
295 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
296 | GCC_WARN_UNUSED_FUNCTION = YES;
297 | GCC_WARN_UNUSED_VARIABLE = YES;
298 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
299 | MTL_ENABLE_DEBUG_INFO = NO;
300 | MTL_FAST_MATH = YES;
301 | SDKROOT = iphoneos;
302 | SWIFT_COMPILATION_MODE = wholemodule;
303 | SWIFT_OPTIMIZATION_LEVEL = "-O";
304 | VALIDATE_PRODUCT = YES;
305 | };
306 | name = Release;
307 | };
308 | 7555FFA6242A565B00829871 /* Debug */ = {
309 | isa = XCBuildConfiguration;
310 | buildSettings = {
311 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
312 | CODE_SIGN_IDENTITY = "Apple Development";
313 | CODE_SIGN_STYLE = Automatic;
314 | DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
315 | DEVELOPMENT_TEAM = "${TEAM_ID}";
316 | ENABLE_PREVIEWS = YES;
317 | FRAMEWORK_SEARCH_PATHS = (
318 | "$(inherited)",
319 | "$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
320 | );
321 | INFOPLIST_FILE = iosApp/Info.plist;
322 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
323 | LD_RUNPATH_SEARCH_PATHS = (
324 | "$(inherited)",
325 | "@executable_path/Frameworks",
326 | );
327 | OTHER_LDFLAGS = (
328 | "$(inherited)",
329 | "-framework",
330 | shared,
331 | );
332 | PRODUCT_BUNDLE_IDENTIFIER = "${BUNDLE_ID}${TEAM_ID}";
333 | PRODUCT_NAME = "${APP_NAME}";
334 | PROVISIONING_PROFILE_SPECIFIER = "";
335 | SWIFT_VERSION = 5.0;
336 | TARGETED_DEVICE_FAMILY = "1,2";
337 | };
338 | name = Debug;
339 | };
340 | 7555FFA7242A565B00829871 /* Release */ = {
341 | isa = XCBuildConfiguration;
342 | buildSettings = {
343 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
344 | CODE_SIGN_IDENTITY = "Apple Development";
345 | CODE_SIGN_STYLE = Automatic;
346 | DEVELOPMENT_ASSET_PATHS = "\"iosApp/Preview Content\"";
347 | DEVELOPMENT_TEAM = "${TEAM_ID}";
348 | ENABLE_PREVIEWS = YES;
349 | FRAMEWORK_SEARCH_PATHS = (
350 | "$(inherited)",
351 | "$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)",
352 | );
353 | INFOPLIST_FILE = iosApp/Info.plist;
354 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
355 | LD_RUNPATH_SEARCH_PATHS = (
356 | "$(inherited)",
357 | "@executable_path/Frameworks",
358 | );
359 | OTHER_LDFLAGS = (
360 | "$(inherited)",
361 | "-framework",
362 | shared,
363 | );
364 | PRODUCT_BUNDLE_IDENTIFIER = "${BUNDLE_ID}${TEAM_ID}";
365 | PRODUCT_NAME = "${APP_NAME}";
366 | PROVISIONING_PROFILE_SPECIFIER = "";
367 | SWIFT_VERSION = 5.0;
368 | TARGETED_DEVICE_FAMILY = "1,2";
369 | };
370 | name = Release;
371 | };
372 | /* End XCBuildConfiguration section */
373 |
374 | /* Begin XCConfigurationList section */
375 | 7555FF76242A565900829871 /* Build configuration list for PBXProject "iosApp" */ = {
376 | isa = XCConfigurationList;
377 | buildConfigurations = (
378 | 7555FFA3242A565B00829871 /* Debug */,
379 | 7555FFA4242A565B00829871 /* Release */,
380 | );
381 | defaultConfigurationIsVisible = 0;
382 | defaultConfigurationName = Release;
383 | };
384 | 7555FFA5242A565B00829871 /* Build configuration list for PBXNativeTarget "iosApp" */ = {
385 | isa = XCConfigurationList;
386 | buildConfigurations = (
387 | 7555FFA6242A565B00829871 /* Debug */,
388 | 7555FFA7242A565B00829871 /* Release */,
389 | );
390 | defaultConfigurationIsVisible = 0;
391 | defaultConfigurationName = Release;
392 | };
393 | /* End XCConfigurationList section */
394 | };
395 | rootObject = 7555FF73242A565900829871 /* Project object */;
396 | }
397 |
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Assets.xcassets/AccentColor.colorset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "colors" : [
3 | {
4 | "idiom" : "universal"
5 | }
6 | ],
7 | "info" : {
8 | "author" : "xcode",
9 | "version" : 1
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "filename" : "app-icon-1024.png",
5 | "idiom" : "universal",
6 | "platform" : "ios",
7 | "size" : "1024x1024"
8 | }
9 | ],
10 | "info" : {
11 | "author" : "xcode",
12 | "version" : 1
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Assets.xcassets/AppIcon.appiconset/app-icon-1024.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/sample/iosApp/iosApp/Assets.xcassets/AppIcon.appiconset/app-icon-1024.png
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/ContentView.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import SwiftUI
3 | import shared
4 |
5 | struct ComposeView: UIViewControllerRepresentable {
6 | func makeUIViewController(context: Context) -> UIViewController {
7 | Main_iosKt.MainViewController()
8 | }
9 |
10 | func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
11 | }
12 |
13 | struct ContentView: View {
14 | var body: some View {
15 | ComposeView()
16 | .ignoresSafeArea(.keyboard) // Compose has own keyboard handler
17 | }
18 | }
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | $(PRODUCT_BUNDLE_PACKAGE_TYPE)
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleVersion
20 | 1
21 | LSRequiresIPhoneOS
22 |
23 | CADisableMinimumFrameDurationOnPhone
24 |
25 | UIApplicationSceneManifest
26 |
27 | UIApplicationSupportsMultipleScenes
28 |
29 |
30 | UILaunchScreen
31 |
32 | UIRequiredDeviceCapabilities
33 |
34 | armv7
35 |
36 | UISupportedInterfaceOrientations
37 |
38 | UIInterfaceOrientationPortrait
39 | UIInterfaceOrientationLandscapeLeft
40 | UIInterfaceOrientationLandscapeRight
41 |
42 | UISupportedInterfaceOrientations~ipad
43 |
44 | UIInterfaceOrientationPortrait
45 | UIInterfaceOrientationPortraitUpsideDown
46 | UIInterfaceOrientationLandscapeLeft
47 | UIInterfaceOrientationLandscapeRight
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/Preview Content/Preview Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
--------------------------------------------------------------------------------
/sample/iosApp/iosApp/iOSApp.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 |
3 | @main
4 | struct iOSApp: App {
5 | var body: some Scene {
6 | WindowGroup {
7 | ContentView()
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/sample/shared/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("multiplatform")
3 | id("com.android.library")
4 | id("org.jetbrains.compose")
5 | }
6 |
7 | kotlin {
8 | androidTarget()
9 |
10 | jvm("desktop")
11 |
12 | listOf(
13 | iosX64(),
14 | iosArm64(),
15 | iosSimulatorArm64(),
16 | ).forEach { iosTarget ->
17 | iosTarget.binaries.framework {
18 | baseName = "shared"
19 | isStatic = true
20 | }
21 | }
22 |
23 | sourceSets {
24 | val commonMain by getting {
25 | dependencies {
26 | implementation(compose.runtime)
27 | implementation(compose.foundation)
28 | implementation(compose.material)
29 | @OptIn(org.jetbrains.compose.ExperimentalComposeLibrary::class)
30 | implementation(compose.components.resources)
31 | // implementation(project(":ktor-boost"))
32 | }
33 | }
34 | val androidMain by getting {
35 | dependencies {
36 | api("androidx.activity:activity-compose:1.7.2")
37 | api("androidx.appcompat:appcompat:1.6.1")
38 | api("androidx.core:core-ktx:1.10.1")
39 | }
40 | }
41 | val iosX64Main by getting
42 | val iosArm64Main by getting
43 | val iosSimulatorArm64Main by getting
44 | val iosMain by creating {
45 | dependsOn(commonMain)
46 | iosX64Main.dependsOn(this)
47 | iosArm64Main.dependsOn(this)
48 | iosSimulatorArm64Main.dependsOn(this)
49 | }
50 | val desktopMain by getting {
51 | dependencies {
52 | implementation(compose.desktop.common)
53 | }
54 | }
55 | }
56 | }
57 |
58 | android {
59 | compileSdk = (findProperty("android.compileSdk") as String).toInt()
60 | namespace = "com.androidpoet.ktor.boost.sample"
61 |
62 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
63 | sourceSets["main"].res.srcDirs("src/androidMain/res")
64 | sourceSets["main"].resources.srcDirs("src/commonMain/resources")
65 |
66 | defaultConfig {
67 | minSdk = (findProperty("android.minSdk") as String).toInt()
68 | }
69 | compileOptions {
70 | sourceCompatibility = JavaVersion.VERSION_17
71 | targetCompatibility = JavaVersion.VERSION_17
72 | }
73 | kotlin {
74 | jvmToolchain(17)
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/sample/shared/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/sample/shared/src/androidMain/kotlin/main.android.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.runtime.Composable
2 |
3 | actual fun getPlatformName(): String = "Android"
4 |
5 | @Composable fun MainView() = App()
6 |
--------------------------------------------------------------------------------
/sample/shared/src/commonMain/kotlin/App.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.animation.AnimatedVisibility
2 | import androidx.compose.foundation.Image
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.fillMaxWidth
5 | import androidx.compose.material.Button
6 | import androidx.compose.material.MaterialTheme
7 | import androidx.compose.material.Text
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.getValue
10 | import androidx.compose.runtime.mutableStateOf
11 | import androidx.compose.runtime.remember
12 | import androidx.compose.runtime.setValue
13 | import androidx.compose.ui.Alignment
14 | import androidx.compose.ui.Modifier
15 | import org.jetbrains.compose.resources.ExperimentalResourceApi
16 | import org.jetbrains.compose.resources.painterResource
17 |
18 | @OptIn(ExperimentalResourceApi::class)
19 | @Composable
20 | fun App() {
21 | MaterialTheme {
22 | var greetingText by remember { mutableStateOf("Hello, World!") }
23 | var showImage by remember { mutableStateOf(false) }
24 | Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
25 | Button(onClick = {
26 | greetingText = "Hello, ${getPlatformName()}"
27 | showImage = !showImage
28 | }) {
29 | Text(greetingText)
30 | }
31 | AnimatedVisibility(showImage) {
32 | Image(
33 | painterResource("compose-multiplatform.xml"),
34 | contentDescription = "Compose Multiplatform icon",
35 | )
36 | }
37 | }
38 | }
39 | }
40 |
41 | expect fun getPlatformName(): String
42 |
--------------------------------------------------------------------------------
/sample/shared/src/commonMain/resources/compose-multiplatform.xml:
--------------------------------------------------------------------------------
1 |
6 |
10 |
14 |
18 |
24 |
30 |
36 |
37 |
--------------------------------------------------------------------------------
/sample/shared/src/desktopMain/kotlin/main.desktop.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.desktop.ui.tooling.preview.Preview
2 | import androidx.compose.runtime.Composable
3 |
4 | actual fun getPlatformName(): String = "Desktop"
5 |
6 | @Composable fun MainView() = App()
7 |
8 | @Preview
9 | @Composable
10 | fun AppPreview() {
11 | App()
12 | }
13 |
--------------------------------------------------------------------------------
/sample/shared/src/iosMain/kotlin/main.ios.kt:
--------------------------------------------------------------------------------
1 | import androidx.compose.ui.window.ComposeUIViewController
2 |
3 | actual fun getPlatformName(): String = "iOS"
4 |
5 | fun MainViewController() = ComposeUIViewController { App() }
6 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "Ktor Boost"
2 |
3 | include(":sample:androidApp")
4 | include(":ktor-boost")
5 | include(":sample:desktopApp")
6 | include(":sample:shared")
7 |
8 | pluginManagement {
9 | repositories {
10 | gradlePluginPortal()
11 | mavenCentral()
12 | google()
13 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
14 | }
15 |
16 | plugins {
17 | val kotlinVersion = extra["kotlin.version"] as String
18 | val agpVersion = extra["agp.version"] as String
19 | val composeVersion = extra["compose.version"] as String
20 | val dokkaVersion = extra["dokka.version"] as String
21 | val klintVersion = extra["klint.version"] as String
22 | val mavenPublishVersion = extra["maven-publish.version"] as String
23 |
24 | kotlin("jvm").version(kotlinVersion)
25 | kotlin("multiplatform").version(kotlinVersion)
26 | kotlin("android").version(kotlinVersion)
27 |
28 | id("com.android.application").version(agpVersion)
29 | id("com.android.library").version(agpVersion)
30 |
31 | id("org.jetbrains.compose").version(composeVersion)
32 | id("org.jetbrains.dokka").version(dokkaVersion)
33 | id("org.jlleitschuh.gradle.ktlint").version(klintVersion)
34 | id("com.vanniktech.maven.publish").version(mavenPublishVersion)
35 | }
36 | }
37 |
38 | plugins {
39 | id("org.gradle.toolchains.foojay-resolver-convention") version("0.4.0")
40 | }
41 |
42 | dependencyResolutionManagement {
43 | repositories {
44 | mavenCentral()
45 | google()
46 | maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/tools/ktlint:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndroidPoet/KtorBoost/2cb9497c2f60b20effff5d9ea0303df9966b48f3/tools/ktlint
--------------------------------------------------------------------------------