├── .github
├── ci-gradle.properties
└── workflows
│ └── push.yml
├── .gitignore
├── LICENSE
├── README.md
├── androidApp
├── .gitignore
├── build.gradle.kts
└── src
│ ├── androidTest
│ ├── AndroidManifest.xml
│ └── java
│ │ └── eu
│ │ └── rajniak
│ │ └── cat
│ │ └── android
│ │ └── CatTest.kt
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── eu
│ │ └── rajniak
│ │ └── cat
│ │ └── android
│ │ ├── CatViewerApp.kt
│ │ ├── MainActivity.kt
│ │ ├── ui
│ │ ├── components
│ │ │ ├── DropdownMenu.kt
│ │ │ ├── DropdownMenuItem.kt
│ │ │ └── TopAppBar.kt
│ │ └── theme
│ │ │ ├── Color.kt
│ │ │ ├── Shapes.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ │ └── viewer
│ │ └── CatsUI.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.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-mdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── themes.xml
├── build.gradle.kts
├── config
└── dummy
│ ├── GoogleService-Info.plist
│ └── google-services.json
├── gradle.properties
├── gradle
├── libs.versions.toml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── iosApp
├── .gitignore
├── iosApp.xcodeproj
│ └── project.pbxproj
├── iosApp
│ ├── AppDelegate.swift
│ ├── ContentView.swift
│ ├── Info.plist
│ ├── Scenes
│ │ ├── CatItem.swift
│ │ ├── CatsFilter.swift
│ │ ├── CatsStore.swift
│ │ └── CatsView.swift
│ ├── Services
│ │ └── ImageService.swift
│ ├── Views
│ │ └── AsyncImage.swift
│ └── iOSApp.swift
├── iosAppTests
│ ├── Info.plist
│ └── iosAppTests.swift
└── iosAppUITests
│ ├── Info.plist
│ └── iosAppUITests.swift
├── readme
├── android_demo.gif
└── ios_demo.gif
├── settings.gradle.kts
└── shared
├── build.gradle.kts
└── src
├── androidMain
├── AndroidManifest.xml
└── kotlin
│ └── eu
│ └── rajniak
│ └── cat
│ └── utils
│ ├── AtomicInt.kt
│ ├── AtomicReference.kt
│ ├── DataStoreSettings.kt
│ ├── Settings.kt
│ └── SharedViewModel.kt
├── commonMain
└── kotlin
│ └── eu
│ └── rajniak
│ └── cat
│ ├── CatViewerServiceLocator.kt
│ ├── CatsApi.kt
│ ├── CatsStore.kt
│ ├── CatsViewModel.kt
│ ├── SettingsStorage.kt
│ ├── data
│ ├── Cat.kt
│ ├── Category.kt
│ ├── CategoryModel.kt
│ ├── FakeData.kt
│ ├── MimeType.kt
│ ├── MimeTypeModel.kt
│ └── MimeTypesSource.kt
│ └── utils
│ ├── AtomicInt.kt
│ ├── AtomicReference.kt
│ ├── CommonFlow.kt
│ ├── Settings.kt
│ └── SharedViewModel.kt
├── commonTest
└── kotlin
│ └── eu
│ └── rajniak
│ └── cat
│ └── CatsTest.kt
└── iosMain
└── kotlin
└── eu
└── rajniak
└── cat
└── utils
├── AtomicInt.kt
├── AtomicReference.kt
├── Settings.kt
├── SharedViewModel.kt
└── UIDispatcher.kt
/.github/ci-gradle.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2020 The Android Open Source Project
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License");
5 | # you may not use this file except in compliance with the License.
6 | # You may obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | # See the License for the specific language governing permissions and
14 | # limitations under the License.
15 | #
16 |
17 | org.gradle.daemon=false
18 | org.gradle.parallel=true
19 | org.gradle.jvmargs=-Xmx5120m
20 | org.gradle.workers.max=2
21 |
22 | kotlin.incremental=false
23 | kotlin.compiler.execution.strategy=in-process
24 |
25 | # expecting catsApiKeyHere
26 |
--------------------------------------------------------------------------------
/.github/workflows/push.yml:
--------------------------------------------------------------------------------
1 | name: Check
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 | # not using macos-latest since it isn't latest at the moment ;) https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners
8 | runs-on: macos-11
9 | environment: common
10 | timeout-minutes: 60
11 |
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v1
15 |
16 | - name: Set CI gradle.properties
17 | env:
18 | CATS_API_KEY: ${{ secrets.CATS_API_KEY }}
19 | run: |
20 | mkdir -p ~/.gradle
21 | cp .github/ci-gradle.properties ~/.gradle/gradle.properties
22 | echo "catsApiKey=${CATS_API_KEY}" >> ~/.gradle/gradle.properties
23 |
24 | - name: Setup Google Services for Firebase
25 | env:
26 | ANDROID_GOOGLE_SERVICES: ${{ secrets.ANDROID_GOOGLE_SERVICES }}
27 | IOS_GOOGLE_SERVICES: ${{ secrets.IOS_GOOGLE_SERVICES }}
28 | run: |
29 | echo $ANDROID_GOOGLE_SERVICES | base64 --decode > androidApp/google-services.json
30 | echo $IOS_GOOGLE_SERVICES | base64 --decode > iosApp/iosApp/GoogleService-Info.plist
31 |
32 | - name: Setup Java JDK
33 | uses: actions/setup-java@v2.1.0
34 | with:
35 | distribution: 'adopt'
36 | java-version: '11'
37 |
38 | # Selecting 13.2.1 (13.1 is default) - https://github.com/actions/virtual-environments/blob/macOS-10.15/20211220.1/images/macos/macos-11-Readme.md
39 | - name: Select Xcode
40 | uses: devbotsxyz/xcode-select@v1
41 |
42 | - name: Build the project
43 | run: ./gradlew build lint --stacktrace
44 |
45 | - name: Upload build reports
46 | if: always()
47 | uses: actions/upload-artifact@v2
48 | with:
49 | name: build-reports
50 | path: |
51 | androidApp/build/reports
52 | shared/build/reports
53 |
54 | - name: Xcode build
55 | run: xcodebuild -project "iosApp/iosApp.xcodeproj" -scheme iosApp test -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 12'
56 |
57 | test:
58 | needs: build
59 | runs-on: macos-11 # enables hardware acceleration in the virtual machine
60 | environment: common
61 | timeout-minutes: 60
62 | strategy:
63 | matrix:
64 | api-level: [23, 29]
65 |
66 | steps:
67 | - name: Checkout
68 | uses: actions/checkout@v2
69 |
70 | - name: Copy CI gradle.properties
71 | run: |
72 | mkdir -p ~/.gradle
73 | cp .github/ci-gradle.properties ~/.gradle/gradle.properties
74 | echo "catsApiKey=${CATS_API_KEY}" >> ~/.gradle/gradle.properties
75 |
76 | - name: Set up JDK 11
77 | uses: actions/setup-java@v1
78 | with:
79 | java-version: 11
80 |
81 | - name: Setup Google Services for Firebase
82 | shell: bash
83 | env:
84 | ANDROID_GOOGLE_SERVICES: ${{ secrets.ANDROID_GOOGLE_SERVICES }}
85 | run: |
86 | echo $ANDROID_GOOGLE_SERVICES | base64 --decode > androidApp/google-services.json
87 |
88 | - name: Run instrumentation tests
89 | uses: reactivecircus/android-emulator-runner@v2
90 | with:
91 | api-level: ${{ matrix.api-level }}
92 | arch: x86
93 | disable-animations: true
94 | script: ./gradlew :androidApp:connectedCheck --stacktrace
95 |
96 | - name: Upload test reports
97 | if: always()
98 | uses: actions/upload-artifact@v2
99 | with:
100 | name: test-reports
101 | path: androidApp/build/reports
102 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | .idea
5 | .DS_Store
6 | /build
7 | */build
8 | /captures
9 | .externalNativeBuild
10 | .cxx
11 | local.properties
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CatViewerDemo
2 | 
3 |
4 | Android demo | iOS demo
5 | :--------------------------------------------------------------------:|:-------------------------------------------------------------:
6 |
|
7 |
8 |
9 |
10 | Kotlin Multiplatform Mobile demo for Android and iOS.
11 | App for viewing Cat pictures from [Cats API](https://thecatapi.com).
12 |
13 | This sample showcases:
14 | * [Kotlin Multiplatform Mobile](https://kotlinlang.org/docs/kmm-overview.html)
15 | * [Android Architecture](https://developer.android.com/jetpack/guide)
16 | * Shared state management with [Flow](https://kotlinlang.org/docs/flow.html)
17 | * Networking with [Ktor](https://ktor.io)
18 | * Persisting state with [Multiplatform Settings](https://github.com/russhwolf/multiplatform-settings)
19 | * Logging with [Kermit](https://github.com/touchlab/Kermit)
20 | * Android UI with [Jetpack Compose](https://developer.android.com/jetpack/compose)
21 | * iOS UI with [SwiftUI](https://developer.apple.com/xcode/swiftui/)
22 | * Android image (GIF) loading with [Coil](https://coil-kt.github.io/coil/)
23 | * UI tests
24 | * Unit tests
25 |
26 | ## Usage
27 | I leave here some notes that might help anyone who would like to build it themselves.
28 |
29 | ### Cats API key
30 | The project is using a property named `catsApiKey` to retrieve the key for the API.
31 |
32 | You can provide it through `gradle.properties`, for example.
33 |
34 | ### Kotlin Multiplatform Mobile setup
35 | You should follow [KMM setup](https://kotlinlang.org/docs/kmm-setup.html)
36 | to build the application, both for Android and iOS.
37 |
38 | ### Google Services
39 | Google Services configuration file is required for Crashlytics, which the app uses to report issues to the authors.
40 | If you want to build and run the app, you need to create your own Firebase project:
41 |
42 | 1. Create a project on [Firebase console](https://console.firebase.google.com/).
43 | 2. Add applications using the package name `eu.rajniak.cat.android` for Android and `eu.rajniak.cat.iosApp` for iOS.
44 | 3. Follow the instructions and download the configuration file to the appropriate folder.
45 | Refer to [setup Android](https://firebase.google.com/docs/android/setup) or [setup iOS](https://firebase.google.com/docs/ios/setup) for further details.
46 | 4. Enable Crashlytics on the Firebase console.
47 |
48 | In case you don't want to create a new Firebase project,
49 | you can still build applications with [dummy configuration files](config/dummy).
50 | Keep in mind that applications with this config will not run.
51 |
52 | This guide is inspired by [code-with-the-italians/bundel](https://github.com/code-with-the-italians/bundel/blob/main/CONTRIBUTING.md).
53 |
54 | ### Dependency updates
55 | To keep dependencies updated [Version Catalog Update Plugin](https://github.com/littlerobots/version-catalog-update-plugin) is used.
56 |
57 | All you need to do is to run `./gradlew versionCatalogUpdate`.
58 |
59 | ## Overview
60 | The goal of the exercise was to build Kotlin Multiplatform Mobile applications for Android and iOS,
61 | with only UI written in platform-specific code (ComposeUI and SwiftUI).
62 |
63 | Everything from ViewModel to Repository and data sources is shared.
64 |
65 | ## Architecture
66 | Architecture follows the standard blueprint proposed in
67 | [Guide to app architecture](https://developer.android.com/jetpack/guide).
68 |
69 | ### Shared module
70 | The shared module consists of Kotlin Multiplatform code that I use to share business and presentation logic
71 | between Android and iOS.
72 |
73 | #### ViewModel
74 | CatsViewModel is the class that UI platform-specific code interacts with.
75 | It prepares cats data displayed in the UI. It also listens to the actions that happen in UI.
76 |
77 | It extends SharedViewModel that provides shared scope for coroutine work.
78 | I took inspiration from [MOKO MVVM library](https://github.com/icerockdev/moko-mvvm),
79 | which I plan to use instead once there is more time.
80 |
81 | #### Repository
82 | CatsStore is responsible for providing Cats model data.
83 | It fetches data from CatsApi and to map it
84 | to model data used in application.
85 |
86 | In the future, I might use the Mapper pattern for mapping data from external systems to domain models.
87 |
88 | Data from CatsApi is intentionally not persisted,
89 | to provide up-to-date results.
90 |
91 | #### CatsApi
92 | CatsApi uses Ktor to fetch data from [Cats API](https://thecatapi.com).
93 |
94 | #### SettingsStorage
95 | SettingsStorage provides platform specific implementations for key value storage.
96 | On Android it is [Datastore](https://developer.android.com/topic/libraries/architecture/datastore).
97 |
98 | #### CatViewerServiceLocator
99 | All dependencies are provided by CatViewerServiceLocator.
100 | For such a small application, it perfectly serves its purpose.
101 |
102 | For larger applications, I would recommend
103 | [Hilt (DI library)](https://developer.android.com/training/dependency-injection/hilt-android).
104 |
105 | ### Android platform-specific UI
106 |
107 | MainActivity is a single activity in the application
108 | as the only application entry point. Even with more screens,
109 | I would still recommend using single activity
110 | as screens can be represented as composable functions now.
111 |
112 | CatsUI file
113 | and composable function currently represent the only screen in the application.
114 | I divided the file into multiple functions for clarity.
115 |
116 | ### iOS platform specific UI
117 |
118 | CatsView is single screen displaying list of Cats.
119 | Cats are represented by CatItem view. For filtering,
120 | view has been created and is displayed as a sheet.
121 |
122 | CatsStore serves as adapter between Kotlin Flow world and SwiftUI.
123 |
124 | ### Tests
125 | Shared code has one test file with a bunch of basic unit tests.
126 | You can find them in CatsTest.
127 |
128 | I test the shared code through the ViewModel interface and
129 | I use Fakes for external systems like networking and IO.
130 |
131 | It allows us to test most of the business logic from a single interface.
132 | Once I add more logic to tested objects, I might need to write more isolated tests.
133 |
134 | There is also one UI instrumentation test in the Android application module.
135 | It runs with dummy ComponentActivity provided by the test library.
136 | It allows us to test the UI in isolation.
137 |
138 | ## Special thanks
139 | This project was way simpler thanks to all the resources,
140 | libraries and projects I was able to find on this topic.
141 |
142 | ### CatsAPI
143 | First and foremost, thanks to the people that created and maintained
144 | a free public service API that I could use to showcase KMM.
145 |
146 | ### John O'Reilly
147 | His [repositories](https://github.com/joreilly) that showcase Kotlin Multiplatform were crucial to my work.
148 |
149 | Especially, [repository](https://github.com/joreilly/MortyComposeKMM) that demonstrates paging.
150 | I could not use the same multiplatform paging library (time constraints),
151 | but I want to try it in the future.
152 |
153 | ### Touchlab
154 | People at [Touchlab](https://touchlab.co) and all the resources they provide publicly
155 | were especially helpful for my understanding of how Kotlin native threading works.
156 |
157 | ### Jetbrains and community
158 | During the project, I was using Apple M1 Silicon and with it arm64 simulators.
159 | Support in libraries is getting better, but the community on #kotlin-lang Slack channel,
160 | was extremely helpful when I was fighting with this.
161 |
162 | ### Others
163 | Special thanks also to all people that share their solutions around Kotlin Multiplatform.
164 | It is hard to find any up-to-date resources, so every single one of them counts.
165 |
166 | Thanks to all the Kotlin Multiplatform libraries out there.
167 | I used:
168 | - [Multiplatform Settings](https://github.com/russhwolf/multiplatform-settings)
169 | - [Kermit](https://github.com/touchlab/Kermit)
170 | - [Kotlin Multiplatform UUID](https://github.com/benasher44/uuid/)
171 | - [BuildKonfig](https://github.com/yshrsmz/BuildKonfig)
172 |
173 | ## TODO
174 | Some things were left undone.
175 |
176 | ### GIFs
177 | [Coil](https://coil-kt.github.io/coil/) on Android helps us with displaying GIFs,
178 | but this has not yet been implemented on iOS.
179 |
180 | ### Caching
181 | [Coil](https://coil-kt.github.io/coil/) on Android is already caching images on disk,
182 | but there is no caching of images on iOS.
183 |
184 | ### Error Handling
185 | There is almost no error handling implemented at the moment.
186 |
187 | It would be nice to show errors when image loading fails,
188 | there is a network issue, etc.
189 |
190 | ### Full-screen view
191 | It would be nice to be able to display images on full screen.
192 |
193 | I could showcase [Navigation with Compose](https://developer.android.com/jetpack/compose/navigation),
194 | since I would have another screen.
195 |
196 | ### Continuous Integration
197 | I believe that even when developing a project alone,
198 | Continuous Integration service can help.
199 |
200 | I would at least know that the build, tests and static analysis run with every new commit.
201 |
202 | Another advantage is that I can be sure that someone else (another machine) can build it.
203 |
204 | GitHub should be able to provide this functionality.
205 |
206 | ### UI improvements
207 | There is a lot of work on UI.
208 |
209 | One thing that stands out is filtering,
210 | I don't think it is intuitive at this point.
211 | But it is there primarily to show work with Flows,
212 | so it is OK for now.
213 |
214 | ### Bugs
215 | There are probably a lot of bugs, but one stands out.
216 |
217 | Pagination, loading of new images is working nicely.
218 | But only when the user scrolls to the bottom of the list.
219 |
220 | But new images are not loaded when the user gets to the bottom
221 | by filtering.
222 |
--------------------------------------------------------------------------------
/androidApp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /google-services.json
--------------------------------------------------------------------------------
/androidApp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.firebase.crashlytics)
4 | alias(libs.plugins.google.services)
5 | alias(libs.plugins.kotlin.android)
6 | }
7 |
8 | dependencies {
9 | implementation(projects.shared)
10 |
11 | // Firebase
12 | implementation (platform(libs.firebase.bom))
13 | implementation(libs.firebase.analytics)
14 | implementation(libs.firebase.crashlytics)
15 |
16 | // Coil
17 | implementation(libs.coil.compose)
18 | implementation(libs.coil.gif)
19 |
20 | // Accompanist
21 | implementation(libs.accompanist.insets.ui)
22 |
23 | // Compose
24 | implementation(libs.androidx.activity.compose)
25 |
26 | implementation(libs.androidx.compose.ui)
27 | implementation(libs.androidx.compose.ui.tooling)
28 | implementation(libs.androidx.compose.foundation)
29 | implementation(libs.androidx.compose.material)
30 | implementation(libs.androidx.compose.material.icons.core)
31 | implementation(libs.androidx.compose.material.icons.extended )
32 |
33 | // UI Tests
34 | androidTestImplementation( libs.androidx.test.junit)
35 | androidTestImplementation(libs.androidx.test.espresso.core)
36 | androidTestImplementation(libs.androidx.compose.ui.test.junit4)
37 | androidTestImplementation(libs.androidx.test.runner)
38 | androidTestUtil(libs.androidx.test.orchestrator)
39 | debugImplementation(libs.androidx.compose.ui.tooling)
40 | debugImplementation(libs.androidx.compose.ui.test.manifest)
41 | }
42 |
43 | android {
44 | compileSdkVersion(31)
45 | defaultConfig {
46 | applicationId = "eu.rajniak.cat.android"
47 | minSdkVersion(23)
48 | targetSdkVersion(30)
49 | versionCode = 1
50 | versionName = "1.0"
51 |
52 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
53 | testInstrumentationRunnerArguments += mapOf(
54 | "clearPackageData" to "true"
55 | )
56 | }
57 | buildFeatures {
58 | compose = true
59 | }
60 | compileOptions {
61 | sourceCompatibility = JavaVersion.VERSION_1_8
62 | targetCompatibility = JavaVersion.VERSION_1_8
63 | }
64 | kotlinOptions {
65 | jvmTarget = "1.8"
66 | }
67 |
68 | composeOptions {
69 | kotlinCompilerExtensionVersion = libs.versions.androidx.compose.get()
70 | }
71 | buildTypes {
72 | getByName("release") {
73 | isMinifyEnabled = false
74 | }
75 | }
76 | testOptions {
77 | animationsDisabled = true
78 | execution = "ANDROIDX_TEST_ORCHESTRATOR"
79 | }
80 | packagingOptions {
81 | resources {
82 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/androidApp/src/androidTest/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/androidApp/src/androidTest/java/eu/rajniak/cat/android/CatTest.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android
2 |
3 | import androidx.compose.ui.test.assertAll
4 | import androidx.compose.ui.test.assertAny
5 | import androidx.compose.ui.test.hasTestTag
6 | import androidx.compose.ui.test.junit4.ComposeTestRule
7 | import androidx.compose.ui.test.junit4.createComposeRule
8 | import androidx.compose.ui.test.onAllNodesWithContentDescription
9 | import androidx.compose.ui.test.performClick
10 | import eu.rajniak.cat.CatsViewModel
11 | import eu.rajniak.cat.android.ui.theme.CatViewerDemoTheme
12 | import eu.rajniak.cat.android.viewer.CatsUI
13 | import org.junit.Rule
14 | import org.junit.Test
15 | import java.util.concurrent.TimeUnit
16 |
17 | // TODO: share hardcoded values so that we won't forget to change them
18 | // on both places
19 | class CatsTest {
20 |
21 | @get:Rule
22 | val composeTestRule = createComposeRule()
23 |
24 | @Test
25 | fun testMimeTypeFilter() {
26 | composeTestRule.setContent {
27 | CatViewerDemoTheme {
28 | CatsUI(CatsViewModel())
29 | }
30 | }
31 |
32 | // TODO: this is flaky because it might take longer than 5s to load
33 | // and also we might get pictures without jpgs
34 | // (running re-runs help with this)
35 | // Make sure there are some jpg pictures loaded
36 | composeTestRule.waitForAssertion() {
37 | composeTestRule
38 | .onAllNodesWithContentDescription("Cat")
39 | .assertAny(hasTestTag("jpg"))
40 | }
41 |
42 | composeTestRule.onNode(hasTestTag("DropdownIconButton")).performClick()
43 | // Filter out jpg
44 | composeTestRule.onNode(hasTestTag("2")).performClick()
45 |
46 | // Make sure there no jpgs anymore
47 | composeTestRule.waitForAssertion() {
48 | composeTestRule
49 | .onAllNodesWithContentDescription("Cat")
50 | .assertAll(!hasTestTag("jpg"))
51 | }
52 | }
53 | }
54 |
55 | fun ComposeTestRule.waitForAssertion(timeoutMillis: Long = TimeUnit.MINUTES.toMillis(1), assertion: () -> Unit) {
56 | waitUntil(timeoutMillis) {
57 | try {
58 | assertion.invoke()
59 | true
60 | } catch (error: AssertionError) {
61 | false
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/androidApp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/CatViewerApp.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android
2 |
3 | import android.app.Application
4 | import co.touchlab.kermit.ExperimentalKermitApi
5 | import co.touchlab.kermit.Logger
6 | import co.touchlab.kermit.crashlytics.CrashlyticsLogWriter
7 | import co.touchlab.kermit.platformLogWriter
8 |
9 | class CatViewerApp : Application() {
10 |
11 | @OptIn(ExperimentalKermitApi::class)
12 | override fun onCreate() {
13 | super.onCreate()
14 | // Setup crash crash reporting service and static log writer on app creation
15 | Logger.setLogWriters(platformLogWriter(), CrashlyticsLogWriter())
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.activity.viewModels
7 | import androidx.core.view.WindowCompat
8 | import co.touchlab.kermit.Logger
9 | import com.google.accompanist.insets.ProvideWindowInsets
10 | import eu.rajniak.cat.CatsViewModel
11 | import eu.rajniak.cat.android.ui.theme.CatViewerDemoTheme
12 | import eu.rajniak.cat.android.viewer.CatsUI
13 |
14 | class MainActivity : ComponentActivity() {
15 |
16 | private val viewModel: CatsViewModel by viewModels()
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 |
21 | Logger.withTag("MainActivity").i("onCreate")
22 |
23 | WindowCompat.setDecorFitsSystemWindows(window, false)
24 |
25 | setContent {
26 | CatViewerDemoTheme {
27 | ProvideWindowInsets(windowInsetsAnimationsEnabled = true) {
28 | CatsUI(viewModel)
29 | }
30 | }
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/components/DropdownMenu.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.components
2 |
3 | import androidx.compose.material.DropdownMenu
4 | import androidx.compose.material.IconButton
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.runtime.getValue
7 | import androidx.compose.runtime.mutableStateOf
8 | import androidx.compose.runtime.remember
9 | import androidx.compose.runtime.setValue
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.platform.testTag
12 |
13 | /**
14 | * Version of [androidx.compose.material.DropdownMenu] with icon.
15 | */
16 | @Composable
17 | fun DropdownMenu(
18 | icon: @Composable () -> Unit,
19 | content: @Composable () -> Unit
20 | ) {
21 | var showMenu by remember { mutableStateOf(false) }
22 |
23 | IconButton(
24 | onClick = { showMenu = true },
25 | modifier = Modifier.testTag("DropdownIconButton")
26 | ) {
27 | icon()
28 | }
29 | DropdownMenu(
30 | expanded = showMenu,
31 | onDismissRequest = { showMenu = false }
32 | ) {
33 | content()
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/components/DropdownMenuItem.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.components
2 |
3 | import androidx.compose.foundation.layout.PaddingValues
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.RowScope
6 | import androidx.compose.foundation.layout.fillMaxWidth
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.foundation.layout.sizeIn
9 | import androidx.compose.material.ContentAlpha
10 | import androidx.compose.material.LocalContentAlpha
11 | import androidx.compose.material.MaterialTheme
12 | import androidx.compose.material.MenuDefaults
13 | import androidx.compose.material.ProvideTextStyle
14 | import androidx.compose.runtime.Composable
15 | import androidx.compose.runtime.CompositionLocalProvider
16 | import androidx.compose.ui.Alignment
17 | import androidx.compose.ui.Modifier
18 | import androidx.compose.ui.unit.dp
19 |
20 | /**
21 | * Non-clickable version of [androidx.compose.material.DropdownMenuItem].
22 | */
23 | @Composable
24 | fun DropdownMenuItem(
25 | modifier: Modifier = Modifier,
26 | enabled: Boolean = true,
27 | contentPadding: PaddingValues = MenuDefaults.DropdownMenuItemContentPadding,
28 | content: @Composable RowScope.() -> Unit
29 | ) {
30 | Row(
31 | modifier = modifier
32 | .fillMaxWidth()
33 | // Preferred min and max width used during the intrinsic measurement.
34 | .sizeIn(
35 | minWidth = DropdownMenuItemDefaultMinWidth,
36 | maxWidth = DropdownMenuItemDefaultMaxWidth,
37 | minHeight = DropdownMenuItemDefaultMinHeight
38 | )
39 | .padding(contentPadding),
40 | verticalAlignment = Alignment.CenterVertically
41 | ) {
42 | val typography = MaterialTheme.typography
43 | ProvideTextStyle(typography.subtitle1) {
44 | val contentAlpha = if (enabled) ContentAlpha.high else ContentAlpha.disabled
45 | CompositionLocalProvider(LocalContentAlpha provides contentAlpha) {
46 | content()
47 | }
48 | }
49 | }
50 | }
51 |
52 | private val DropdownMenuItemDefaultMinWidth = 112.dp
53 | private val DropdownMenuItemDefaultMaxWidth = 280.dp
54 | private val DropdownMenuItemDefaultMinHeight = 48.dp
55 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/components/TopAppBar.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.components
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.PaddingValues
5 | import androidx.compose.foundation.layout.Row
6 | import androidx.compose.foundation.layout.RowScope
7 | import androidx.compose.foundation.layout.fillMaxHeight
8 | import androidx.compose.foundation.layout.width
9 | import androidx.compose.material.AppBarDefaults
10 | import androidx.compose.material.ContentAlpha
11 | import androidx.compose.material.LocalContentAlpha
12 | import androidx.compose.material.TopAppBar
13 | import androidx.compose.runtime.Composable
14 | import androidx.compose.runtime.CompositionLocalProvider
15 | import androidx.compose.ui.Alignment
16 | import androidx.compose.ui.Modifier
17 | import androidx.compose.ui.unit.dp
18 |
19 | @Composable
20 | fun TopAppBar(
21 | navigationIcon: @Composable (() -> Unit),
22 | title: @Composable () -> Unit,
23 | actions: @Composable RowScope.() -> Unit = {},
24 | contentPadding: PaddingValues = AppBarDefaults.ContentPadding,
25 | ) {
26 | TopAppBar(
27 | contentPadding = contentPadding
28 | ) {
29 | Row(
30 | modifier = TitleIconModifier,
31 | verticalAlignment = Alignment.CenterVertically
32 | ) {
33 | CompositionLocalProvider(
34 | LocalContentAlpha provides ContentAlpha.high,
35 | content = navigationIcon
36 | )
37 | }
38 |
39 | Row(
40 | Modifier
41 | .fillMaxHeight()
42 | .weight(1f),
43 | verticalAlignment = Alignment.CenterVertically
44 | ) {
45 | title()
46 | }
47 |
48 | CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
49 | Row(
50 | Modifier.fillMaxHeight(),
51 | horizontalArrangement = Arrangement.End,
52 | verticalAlignment = Alignment.CenterVertically,
53 | content = actions
54 | )
55 | }
56 | }
57 | }
58 |
59 | private val AppBarHorizontalPadding = 4.dp
60 |
61 | // Start inset for the title when there is a navigation icon provided
62 | private val TitleIconModifier = Modifier
63 | .fillMaxHeight()
64 | .width(56.dp - AppBarHorizontalPadding)
65 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple200 = Color(0xFFBB86FC)
6 | val Purple500 = Color(0xFF6200EE)
7 | val Purple700 = Color(0xFF3700B3)
8 | val Teal200 = Color(0xFF03DAC5)
9 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/theme/Shapes.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.theme
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.material.Shapes
5 | import androidx.compose.ui.unit.dp
6 |
7 | val Shapes = Shapes(
8 | small = RoundedCornerShape(4.dp),
9 | medium = RoundedCornerShape(4.dp),
10 | large = RoundedCornerShape(0.dp)
11 | )
12 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material.MaterialTheme
5 | import androidx.compose.material.darkColors
6 | import androidx.compose.material.lightColors
7 | import androidx.compose.runtime.Composable
8 |
9 | private val DarkColorPalette = darkColors(
10 | primary = Purple200,
11 | primaryVariant = Purple700,
12 | secondary = Teal200
13 | )
14 |
15 | private val LightColorPalette = lightColors(
16 | primary = Purple500,
17 | primaryVariant = Purple700,
18 | secondary = Teal200
19 |
20 | /* Other default colors to override
21 | background = Color.White,
22 | surface = Color.White,
23 | onPrimary = Color.White,
24 | onSecondary = Color.Black,
25 | onBackground = Color.Black,
26 | onSurface = Color.Black,
27 | */
28 | )
29 |
30 | @Composable
31 | fun CatViewerDemoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
32 | val colors = if (darkTheme) {
33 | DarkColorPalette
34 | } else {
35 | LightColorPalette
36 | }
37 |
38 | MaterialTheme(
39 | colors = colors,
40 | typography = Typography,
41 | shapes = Shapes,
42 | content = content
43 | )
44 | }
45 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.ui.theme
2 |
3 | import androidx.compose.material.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | body1 = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp
15 | )
16 | /* Other default text styles to override
17 | button = TextStyle(
18 | fontFamily = FontFamily.Default,
19 | fontWeight = FontWeight.W500,
20 | fontSize = 14.sp
21 | ),
22 | caption = TextStyle(
23 | fontFamily = FontFamily.Default,
24 | fontWeight = FontWeight.Normal,
25 | fontSize = 12.sp
26 | )
27 | */
28 | )
29 |
--------------------------------------------------------------------------------
/androidApp/src/main/java/eu/rajniak/cat/android/viewer/CatsUI.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.android.viewer
2 |
3 | import android.os.Build.VERSION.SDK_INT
4 | import androidx.compose.foundation.ExperimentalFoundationApi
5 | import androidx.compose.foundation.Image
6 | import androidx.compose.foundation.layout.Box
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxSize
9 | import androidx.compose.foundation.layout.fillMaxWidth
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.foundation.layout.size
12 | import androidx.compose.foundation.layout.width
13 | import androidx.compose.foundation.lazy.GridCells
14 | import androidx.compose.foundation.lazy.LazyListState
15 | import androidx.compose.foundation.lazy.LazyVerticalGrid
16 | import androidx.compose.foundation.lazy.itemsIndexed
17 | import androidx.compose.foundation.lazy.rememberLazyListState
18 | import androidx.compose.material.Checkbox
19 | import androidx.compose.material.CircularProgressIndicator
20 | import androidx.compose.material.Divider
21 | import androidx.compose.material.Icon
22 | import androidx.compose.material.IconButton
23 | import androidx.compose.material.MaterialTheme
24 | import androidx.compose.material.Scaffold
25 | import androidx.compose.material.Surface
26 | import androidx.compose.material.Text
27 | import androidx.compose.material.icons.Icons
28 | import androidx.compose.material.icons.filled.FilterList
29 | import androidx.compose.material.icons.filled.Menu
30 | import androidx.compose.runtime.Composable
31 | import androidx.compose.runtime.LaunchedEffect
32 | import androidx.compose.runtime.collectAsState
33 | import androidx.compose.runtime.getValue
34 | import androidx.compose.runtime.snapshotFlow
35 | import androidx.compose.ui.Modifier
36 | import androidx.compose.ui.platform.LocalContext
37 | import androidx.compose.ui.platform.testTag
38 | import androidx.compose.ui.res.stringResource
39 | import androidx.compose.ui.semantics.contentDescription
40 | import androidx.compose.ui.semantics.semantics
41 | import androidx.compose.ui.tooling.preview.Preview
42 | import androidx.compose.ui.unit.dp
43 | import coil.ImageLoader
44 | import coil.compose.rememberImagePainter
45 | import coil.decode.GifDecoder
46 | import coil.decode.ImageDecoderDecoder
47 | import com.google.accompanist.insets.LocalWindowInsets
48 | import com.google.accompanist.insets.navigationBarsHeight
49 | import com.google.accompanist.insets.rememberInsetsPaddingValues
50 | import eu.rajniak.cat.CatsViewModel
51 | import eu.rajniak.cat.android.R
52 | import eu.rajniak.cat.android.ui.components.DropdownMenu
53 | import eu.rajniak.cat.android.ui.components.DropdownMenuItem
54 | import eu.rajniak.cat.android.ui.components.TopAppBar
55 | import eu.rajniak.cat.android.ui.theme.CatViewerDemoTheme
56 | import eu.rajniak.cat.data.Cat
57 | import eu.rajniak.cat.data.CategoryModel
58 | import eu.rajniak.cat.data.FakeData
59 | import eu.rajniak.cat.data.MimeTypeModel
60 | import kotlinx.coroutines.flow.collect
61 | import kotlinx.coroutines.flow.distinctUntilChanged
62 | import kotlinx.coroutines.flow.filter
63 |
64 | @Composable
65 | fun CatsUI(viewModel: CatsViewModel) {
66 | val cats by viewModel.cats.collectAsState(listOf())
67 | val categories by viewModel.categories.collectAsState(listOf())
68 | val mimeTypes by viewModel.mimeTypes.collectAsState(listOf())
69 | CatsUI(
70 | cats = cats,
71 | categories = categories,
72 | onCategoryChecked = { categoryId, checked ->
73 | viewModel.onCategoryChecked(categoryId, checked)
74 | },
75 | mimeTypes = mimeTypes,
76 | onMimeTypeChecked = { mimeTypeId, checked ->
77 | viewModel.onMimeTypeChecked(mimeTypeId, checked)
78 | },
79 | onScrolledToTheEnd = { viewModel.onScrolledToTheEnd() }
80 | )
81 | }
82 |
83 | @Composable
84 | fun CatsUI(
85 | cats: List,
86 | categories: List,
87 | onCategoryChecked: (Int, Boolean) -> Unit,
88 | mimeTypes: List,
89 | onMimeTypeChecked: (Int, Boolean) -> Unit,
90 | onScrolledToTheEnd: () -> Unit
91 | ) {
92 | Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
93 | Scaffold(
94 | topBar = {
95 | TopAppBar(
96 | contentPadding = rememberInsetsPaddingValues(
97 | insets = LocalWindowInsets.current.statusBars,
98 | applyStart = true,
99 | applyTop = true,
100 | applyEnd = true,
101 | ),
102 | navigationIcon = {
103 | IconButton(onClick = { }) {
104 | Icon(Icons.Filled.Menu, "menu")
105 | }
106 | },
107 | title = {
108 | Text(
109 | text = stringResource(R.string.app_name),
110 | color = MaterialTheme.colors.onPrimary,
111 | )
112 | },
113 | actions = {
114 | Filter(
115 | categories = categories,
116 | onCategoryChecked = onCategoryChecked,
117 | mimeTypes = mimeTypes,
118 | onMimeTypeChecked = onMimeTypeChecked
119 | )
120 | },
121 | )
122 | },
123 | bottomBar = {
124 | Spacer(
125 | Modifier
126 | .navigationBarsHeight()
127 | .fillMaxWidth()
128 | )
129 | },
130 | ) { contentPadding ->
131 | Box(Modifier.padding(contentPadding)) {
132 | CatsList(
133 | cats = cats,
134 | onScrolledToTheEnd = onScrolledToTheEnd
135 | )
136 | }
137 | }
138 | }
139 | }
140 |
141 | @Composable
142 | private fun Filter(
143 | categories: List,
144 | onCategoryChecked: (Int, Boolean) -> Unit,
145 | mimeTypes: List,
146 | onMimeTypeChecked: (Int, Boolean) -> Unit,
147 | ) {
148 | DropdownMenu(
149 | icon = {
150 | Icon(
151 | imageVector = Icons.Filled.FilterList,
152 | contentDescription = "Filter"
153 | )
154 | }
155 | ) {
156 | CategoryFilter(
157 | categories = categories,
158 | onCategoryChecked = onCategoryChecked
159 | )
160 |
161 | Divider()
162 |
163 | MimeTypeFilter(
164 | mimeTypes = mimeTypes,
165 | onMimeTypeChecked = onMimeTypeChecked
166 | )
167 | }
168 | }
169 |
170 | // TODO: since cat can have multiple categories,
171 | // one category can be enabled while other disabled,
172 | // current behaviour of filtering such item
173 | // might not be intuitive (improve UI)
174 | @Composable
175 | private fun CategoryFilter(
176 | categories: List,
177 | onCategoryChecked: (Int, Boolean) -> Unit,
178 | ) {
179 | categories.forEach { category ->
180 | DropdownMenuItem {
181 | Checkbox(
182 | checked = category.enabled,
183 | onCheckedChange = { checked ->
184 | onCategoryChecked(category.id, checked)
185 | },
186 | )
187 | Spacer(modifier = Modifier.width(8.dp))
188 | Text(category.name)
189 | }
190 | }
191 | }
192 |
193 | @Composable
194 | private fun MimeTypeFilter(
195 | mimeTypes: List,
196 | onMimeTypeChecked: (Int, Boolean) -> Unit,
197 | ) {
198 | mimeTypes.forEach { mimeType ->
199 | DropdownMenuItem {
200 | Checkbox(
201 | checked = mimeType.enabled,
202 | onCheckedChange = { checked ->
203 | onMimeTypeChecked(mimeType.id, checked)
204 | },
205 | modifier = Modifier.testTag(mimeType.id.toString())
206 | )
207 | Spacer(modifier = Modifier.width(8.dp))
208 | Text(mimeType.name)
209 | }
210 | }
211 | }
212 |
213 | @OptIn(ExperimentalFoundationApi::class)
214 | @Composable
215 | fun CatsList(
216 | cats: List,
217 | onScrolledToTheEnd: () -> Unit
218 | ) {
219 | val listState = rememberLazyListState()
220 |
221 | LazyVerticalGrid(
222 | state = listState,
223 | cells = GridCells.Adaptive(minSize = 128.dp)
224 | ) {
225 | itemsIndexed(cats) { _, cat ->
226 | CatItem(cat)
227 | }
228 | item {
229 | CircularProgressIndicator(
230 | // TODO: specify size instead to make progress smaller
231 | modifier = Modifier.padding(48.dp)
232 | )
233 | }
234 | }
235 |
236 | if (cats.isNotEmpty()) {
237 | // TODO: use pagination 3 library (once we have support from shared library)
238 | LaunchedEffect(listState) {
239 | snapshotFlow { listState.isScrolledToTheEnd() }
240 | .distinctUntilChanged()
241 | .filter { it == true }
242 | .collect {
243 | onScrolledToTheEnd()
244 | }
245 | }
246 | }
247 | }
248 |
249 | fun LazyListState.isScrolledToTheEnd() =
250 | layoutInfo.visibleItemsInfo.lastOrNull()?.index == layoutInfo.totalItemsCount - 1
251 |
252 | @Composable
253 | fun CatItem(cat: Cat) {
254 | val context = LocalContext.current
255 | Image(
256 | painter = rememberImagePainter(
257 | data = cat.url,
258 | imageLoader = ImageLoader.Builder(context).componentRegistry {
259 | if (SDK_INT >= 28) {
260 | add(ImageDecoderDecoder(context))
261 | } else {
262 | add(GifDecoder())
263 | }
264 | }.build(),
265 | onExecute = { _, _ -> true },
266 | builder = {
267 | // cannot use crossfade - won't display gif correctly
268 | placeholder(R.drawable.ic_launcher_foreground)
269 | // cannot use modifiers - will make gif to static image
270 | }
271 | ),
272 | modifier = Modifier
273 | .size(128.dp)
274 | .semantics { contentDescription = "Cat" }
275 | .testTag(
276 | when {
277 | cat.url.endsWith(".gif") -> "gif"
278 | cat.url.endsWith(".jpg") -> "jpg"
279 | else -> "other"
280 | }
281 | ),
282 | contentDescription = null // TODO: we can fetch something interesting about the image
283 | )
284 | }
285 |
286 | @Preview(showBackground = true)
287 | @Composable
288 | fun DefaultPreview() {
289 | CatViewerDemoTheme {
290 | CatsUI(
291 | cats = FakeData.cats,
292 | categories = listOf(),
293 | onCategoryChecked = { _, _ -> },
294 | mimeTypes = listOf(),
295 | onMimeTypeChecked = { _, _ -> },
296 | onScrolledToTheEnd = { }
297 | )
298 | }
299 | }
300 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
31 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/androidApp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/androidApp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
11 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Cat Viewer Demo
3 |
--------------------------------------------------------------------------------
/androidApp/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask
2 |
3 | plugins {
4 | alias(libs.plugins.spotless)
5 | alias(libs.plugins.versions)
6 | alias(libs.plugins.version.catalog.update)
7 | }
8 |
9 | buildscript {
10 | repositories {
11 | gradlePluginPortal()
12 | google()
13 | mavenCentral()
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | mavenCentral()
21 | }
22 | }
23 |
24 | subprojects {
25 | apply(plugin = "com.diffplug.spotless")
26 | spotless {
27 | kotlin {
28 | target("**/*.kt")
29 | targetExclude("$buildDir/**/*.kt")
30 | targetExclude("bin/**/*.kt")
31 |
32 | ktlint()
33 | }
34 | }
35 | }
36 |
37 | fun isNonStable(version: String) = listOf(
38 | "alpha", "beta", // Firebase, Avast
39 | "-M" // JUnit Jupiter
40 | ).any { version.contains(it) }
41 |
42 | // Add here dependencies that cannot be updated at the moment
43 | fun cannotUpdate(module: String) = emptyList().any { module.contains(it) }
44 |
45 | tasks.named("dependencyUpdates").configure {
46 | resolutionStrategy {
47 | componentSelection {
48 | all {
49 | if (cannotUpdate(candidate.module)) {
50 | reject("Ignore because we cannot update at the moment.")
51 | }
52 | if (isNonStable(candidate.version) && !isNonStable(currentVersion)) {
53 | reject("Ignore because version is not stable")
54 | }
55 | }
56 | }
57 | }
58 | }
--------------------------------------------------------------------------------
/config/dummy/GoogleService-Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CLIENT_ID
6 | 0000000000000-00000000000000000000000000000000.apps.googleusercontent.com
7 | REVERSED_CLIENT_ID
8 | com.googleusercontent.apps.0000000000000-00000000000000000000000000000000
9 | API_KEY
10 | 000000000000000000000000000000000000000
11 | GCM_SENDER_ID
12 | 000000000000
13 | PLIST_VERSION
14 | 1
15 | BUNDLE_ID
16 | eu.rajniak.cat.iosApp
17 | PROJECT_ID
18 | cat-viewer-00000
19 | STORAGE_BUCKET
20 | cat-viewer-00000.appspot.com
21 | IS_ADS_ENABLED
22 |
23 | IS_ANALYTICS_ENABLED
24 |
25 | IS_APPINVITE_ENABLED
26 |
27 | IS_GCM_ENABLED
28 |
29 | IS_SIGNIN_ENABLED
30 |
31 | GOOGLE_APP_ID
32 | 1:000000000000:ios:0000000000000000000000
33 |
34 |
--------------------------------------------------------------------------------
/config/dummy/google-services.json:
--------------------------------------------------------------------------------
1 | {
2 | "project_info": {
3 | "project_number": "0000000000000",
4 | "project_id": "cat-viewer-00000",
5 | "storage_bucket": "cat-viewer-00000.appspot.com"
6 | },
7 | "client": [
8 | {
9 | "client_info": {
10 | "mobilesdk_app_id": "1:000000000000:android:0000000000000000000000",
11 | "android_client_info": {
12 | "package_name": "eu.rajniak.cat.android"
13 | }
14 | },
15 | "oauth_client": [
16 | {
17 | "client_id": "000000000000-00000000000000000000000000000000.apps.googleusercontent.com",
18 | "client_type": 3
19 | }
20 | ],
21 | "api_key": [
22 | {
23 | "current_key": "000000000000000000000000000000000000000",
24 | }
25 | ],
26 | "services": {
27 | "appinvite_service": {
28 | "other_platform_oauth_client": [
29 | {
30 | "client_id": "000000000000-00000000000000000000000000000000.apps.googleusercontent.com",
31 | "client_type": 3
32 | },
33 | {
34 | "client_id": "000000000000-00000000000000000000000000000000.apps.googleusercontent.com",
35 | "client_type": 2,
36 | "ios_info": {
37 | "bundle_id": "eu.rajniak.cat.iosApp"
38 | }
39 | }
40 | ]
41 | }
42 | }
43 | }
44 | ],
45 | "configuration_version": "1"
46 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Gradle
2 | org.gradle.jvmargs=-Xmx2048M -Dkotlin.daemon.jvm.options\="-Xmx2048M"
3 |
4 | #Kotlin
5 | kotlin.code.style=official
6 | kotlin.mpp.stability.nowarn=true
7 | kotlin.native.binary.memoryModel=experimental
8 | kotlin.native.binary.freezing=disabled
9 |
10 | #Android
11 | android.useAndroidX=true
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | android-plugin = "7.1.1"
3 | androidx-compose = "1.1.0"
4 | androidx-test = "1.4.1-alpha03"
5 | coil = "1.4.0"
6 | kermit = "1.0.3"
7 | kotlin = "1.6.10"
8 | kotlinx = "1.6.0"
9 | ktor = "2.0.0-beta-1"
10 | multiplatform-settings = "0.8.1"
11 |
12 | [libraries]
13 | accompanist-insets-ui = "com.google.accompanist:accompanist-insets-ui:0.23.0"
14 | androidx-activity-compose = "androidx.activity:activity-compose:1.4.0"
15 | androidx-compose-foundation = "androidx.compose.foundation:foundation:1.1.0"
16 | androidx-compose-material = { module = "androidx.compose.material:material", version.ref = "androidx-compose" }
17 | androidx-compose-material-icons-core = { module = "androidx.compose.material:material-icons-core", version.ref = "androidx-compose" }
18 | androidx-compose-material-icons-extended = { module = "androidx.compose.material:material-icons-extended", version.ref = "androidx-compose" }
19 | androidx-compose-ui = { module = "androidx.compose.ui:ui", version.ref = "androidx-compose" }
20 | androidx-compose-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx-compose" }
21 | androidx-compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest", version.ref = "androidx-compose" }
22 | androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "androidx-compose" }
23 | androidx-datastore-preferences = "androidx.datastore:datastore-preferences:1.0.0"
24 | androidx-lifecycle-viewmodel = "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1"
25 | androidx-startup-runtime = "androidx.startup:startup-runtime:1.1.1"
26 | androidx-test-espresso-core = "androidx.test.espresso:espresso-core:3.4.0"
27 | androidx-test-junit = "androidx.test.ext:junit:1.1.3"
28 | androidx-test-orchestrator = { module = "androidx.test:orchestrator", version.ref = "androidx-test" }
29 | androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test" }
30 | coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coil" }
31 | coil-gif = { module = "io.coil-kt:coil-gif", version.ref = "coil" }
32 | firebase-analytics = { module = "com.google.firebase:firebase-analytics-ktx" }
33 | firebase-bom = "com.google.firebase:firebase-bom:29.0.4"
34 | firebase-crashlytics = { module = "com.google.firebase:firebase-crashlytics-ktx" }
35 | junit = "junit:junit:4.13.2"
36 | kermit = { module = "co.touchlab:kermit", version.ref = "kermit" }
37 | kermit-crashlytics = { module = "co.touchlab:kermit-crashlytics", version.ref = "kermit" }
38 | kermit-test = { module = "co.touchlab:kermit-test", version.ref = "kermit" }
39 | kotlin-serialization-plugin = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" }
40 | kotlin-test-annotations-common = { module = "org.jetbrains.kotlin:kotlin-test-annotations-common", version.ref = "kotlin" }
41 | kotlin-test-common = { module = "org.jetbrains.kotlin:kotlin-test-common", version.ref = "kotlin" }
42 | kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
43 | kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx" }
44 | kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx" }
45 | ktor-client-android = { module = "io.ktor:ktor-client-android", version.ref = "ktor" }
46 | ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
47 | ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
48 | ktor-client-ios = { module = "io.ktor:ktor-client-ios", version.ref = "ktor" }
49 | ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
50 | multiplatform-settings-coroutines = { module = "com.russhwolf:multiplatform-settings-coroutines", version.ref = "multiplatform-settings" }
51 | multiplatform-settings-test = { module = "com.russhwolf:multiplatform-settings-test", version.ref = "multiplatform-settings" }
52 | uuid = "com.benasher44:uuid:0.4.0"
53 |
54 | [plugins]
55 | android-application = { id = "com.android.application", version.ref = "android-plugin" }
56 | android-library = { id = "com.android.library", version.ref = "android-plugin" }
57 | buildkonfig = "com.codingfeline.buildkonfig:0.11.0"
58 | firebase-crashlytics = "com.google.firebase.crashlytics:2.8.1"
59 | google-services = "com.google.gms.google-services:4.3.10"
60 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
61 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
62 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
63 | spotless = "com.diffplug.spotless:6.2.2"
64 | version-catalog-update = "nl.littlerobots.version-catalog-update:0.3.0"
65 | versions = "com.github.ben-manes.versions:0.42.0"
66 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/iosApp/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.toptal.com/developers/gitignore/api/xcode,swift,objective-c
2 | # Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift,objective-c
3 |
4 | ### Objective-C ###
5 | # Xcode
6 | #
7 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
8 |
9 | ## User settings
10 | xcuserdata/
11 |
12 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
13 | *.xcscmblueprint
14 | *.xccheckout
15 |
16 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
17 | build/
18 | DerivedData/
19 | *.moved-aside
20 | *.pbxuser
21 | !default.pbxuser
22 | *.mode1v3
23 | !default.mode1v3
24 | *.mode2v3
25 | !default.mode2v3
26 | *.perspectivev3
27 | !default.perspectivev3
28 |
29 | ## Obj-C/Swift specific
30 | *.hmap
31 |
32 | ## App packaging
33 | *.ipa
34 | *.dSYM.zip
35 | *.dSYM
36 |
37 | # CocoaPods
38 | # We recommend against adding the Pods directory to your .gitignore. However
39 | # you should judge for yourself, the pros and cons are mentioned at:
40 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
41 | # Pods/
42 | # Add this line if you want to avoid checking in source code from the Xcode workspace
43 | # *.xcworkspace
44 |
45 | # Carthage
46 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
47 | # Carthage/Checkouts
48 |
49 | Carthage/Build/
50 |
51 | # fastlane
52 | # It is recommended to not store the screenshots in the git repo.
53 | # Instead, use fastlane to re-generate the screenshots whenever they are needed.
54 | # For more information about the recommended setup visit:
55 | # https://docs.fastlane.tools/best-practices/source-control/#source-control
56 |
57 | fastlane/report.xml
58 | fastlane/Preview.html
59 | fastlane/screenshots/**/*.png
60 | fastlane/test_output
61 |
62 | # Code Injection
63 | # After new code Injection tools there's a generated folder /iOSInjectionProject
64 | # https://github.com/johnno1962/injectionforxcode
65 |
66 | iOSInjectionProject/
67 |
68 | ### Objective-C Patch ###
69 |
70 | ### Swift ###
71 | # Xcode
72 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
73 |
74 |
75 |
76 |
77 |
78 |
79 | ## Playgrounds
80 | timeline.xctimeline
81 | playground.xcworkspace
82 |
83 | # Swift Package Manager
84 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
85 | # Packages/
86 | # Package.pins
87 | # Package.resolved
88 | # *.xcodeproj
89 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
90 | # hence it is not needed unless you have added a package configuration file to your project
91 | # .swiftpm
92 |
93 | .build/
94 |
95 | # CocoaPods
96 | # We recommend against adding the Pods directory to your .gitignore. However
97 | # you should judge for yourself, the pros and cons are mentioned at:
98 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
99 | # Pods/
100 | # Add this line if you want to avoid checking in source code from the Xcode workspace
101 | # *.xcworkspace
102 |
103 | # Carthage
104 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
105 | # Carthage/Checkouts
106 |
107 |
108 | # Accio dependency management
109 | Dependencies/
110 | .accio/
111 |
112 | # fastlane
113 | # It is recommended to not store the screenshots in the git repo.
114 | # Instead, use fastlane to re-generate the screenshots whenever they are needed.
115 | # For more information about the recommended setup visit:
116 | # https://docs.fastlane.tools/best-practices/source-control/#source-control
117 |
118 |
119 | # Code Injection
120 | # After new code Injection tools there's a generated folder /iOSInjectionProject
121 | # https://github.com/johnno1962/injectionforxcode
122 |
123 |
124 | ### Xcode ###
125 | # Xcode
126 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
127 |
128 |
129 |
130 |
131 | ## Gcc Patch
132 | /*.gcno
133 |
134 | ### Xcode Patch ###
135 | *.xcodeproj/*
136 | !*.xcodeproj/project.pbxproj
137 | !*.xcodeproj/xcshareddata/
138 | !*.xcworkspace/contents.xcworkspacedata
139 | **/xcshareddata/WorkspaceSettings.xcsettings
140 |
141 | # End of https://www.toptal.com/developers/gitignore/api/xcode,swift,objective-c
142 |
143 | ## Firebase
144 | iosApp/GoogleService-Info.plist
--------------------------------------------------------------------------------
/iosApp/iosApp.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 52;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2152FB032600AC8F00CF470E /* iOSApp.swift */; };
11 | 375300AF27230EA70029761B /* CatsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375300AE27230EA70029761B /* CatsView.swift */; };
12 | 375300B2272310F80029761B /* CatsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375300B1272310F80029761B /* CatsStore.swift */; };
13 | 375300B4272312420029761B /* CatItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375300B3272312420029761B /* CatItem.swift */; };
14 | 375300B7272335AD0029761B /* AsyncImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375300B6272335AD0029761B /* AsyncImage.swift */; };
15 | 375300BA272336540029761B /* ImageService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 375300B9272336540029761B /* ImageService.swift */; };
16 | 376070392752C6B300CFED19 /* iosAppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 376070382752C6B300CFED19 /* iosAppTests.swift */; };
17 | 376070472753FAC000CFED19 /* iosAppUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 376070462753FAC000CFED19 /* iosAppUITests.swift */; };
18 | 376951302725B906001B6E0D /* CatsFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3769512F2725B906001B6E0D /* CatsFilter.swift */; };
19 | 37C3AE112788BF1A00897D2D /* FirebaseAnalyticsSwift-Beta in Frameworks */ = {isa = PBXBuildFile; productRef = 37C3AE102788BF1A00897D2D /* FirebaseAnalyticsSwift-Beta */; };
20 | 37C3AE132788BF1A00897D2D /* FirebaseCrashlytics in Frameworks */ = {isa = PBXBuildFile; productRef = 37C3AE122788BF1A00897D2D /* FirebaseCrashlytics */; };
21 | 37C3AE152788BFF700897D2D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37C3AE142788BFF700897D2D /* AppDelegate.swift */; };
22 | 37C3AE192788C38700897D2D /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 37C3AE182788C38700897D2D /* GoogleService-Info.plist */; };
23 | 7555FF83242A565900829871 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7555FF82242A565900829871 /* ContentView.swift */; };
24 | /* End PBXBuildFile section */
25 |
26 | /* Begin PBXContainerItemProxy section */
27 | 3760703B2752C6B300CFED19 /* PBXContainerItemProxy */ = {
28 | isa = PBXContainerItemProxy;
29 | containerPortal = 7555FF73242A565900829871 /* Project object */;
30 | proxyType = 1;
31 | remoteGlobalIDString = 7555FF7A242A565900829871;
32 | remoteInfo = iosApp;
33 | };
34 | 376070492753FAC000CFED19 /* PBXContainerItemProxy */ = {
35 | isa = PBXContainerItemProxy;
36 | containerPortal = 7555FF73242A565900829871 /* Project object */;
37 | proxyType = 1;
38 | remoteGlobalIDString = 7555FF7A242A565900829871;
39 | remoteInfo = iosApp;
40 | };
41 | /* End PBXContainerItemProxy section */
42 |
43 | /* Begin PBXCopyFilesBuildPhase section */
44 | 7555FFB4242A642300829871 /* Embed Frameworks */ = {
45 | isa = PBXCopyFilesBuildPhase;
46 | buildActionMask = 2147483647;
47 | dstPath = "";
48 | dstSubfolderSpec = 10;
49 | files = (
50 | );
51 | name = "Embed Frameworks";
52 | runOnlyForDeploymentPostprocessing = 0;
53 | };
54 | /* End PBXCopyFilesBuildPhase section */
55 |
56 | /* Begin PBXFileReference section */
57 | 2152FB032600AC8F00CF470E /* iOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iOSApp.swift; sourceTree = ""; };
58 | 375300AE27230EA70029761B /* CatsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatsView.swift; sourceTree = ""; };
59 | 375300B1272310F80029761B /* CatsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatsStore.swift; sourceTree = ""; };
60 | 375300B3272312420029761B /* CatItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatItem.swift; sourceTree = ""; };
61 | 375300B6272335AD0029761B /* AsyncImage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncImage.swift; sourceTree = ""; };
62 | 375300B9272336540029761B /* ImageService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageService.swift; sourceTree = ""; };
63 | 3760702A2752C48600CFED19 /* iosAppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosAppTests.swift; sourceTree = ""; };
64 | 3760702C2752C48600CFED19 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
65 | 376070362752C6B300CFED19 /* iosAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iosAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
66 | 376070382752C6B300CFED19 /* iosAppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosAppTests.swift; sourceTree = ""; };
67 | 3760703A2752C6B300CFED19 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
68 | 376070442753FAC000CFED19 /* iosAppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = iosAppUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
69 | 376070462753FAC000CFED19 /* iosAppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = iosAppUITests.swift; sourceTree = ""; };
70 | 376070482753FAC000CFED19 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
71 | 3769512F2725B906001B6E0D /* CatsFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatsFilter.swift; sourceTree = ""; };
72 | 37C3AE142788BFF700897D2D /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
73 | 37C3AE182788C38700897D2D /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; };
74 | 7555FF7B242A565900829871 /* iosApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iosApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
75 | 7555FF82242A565900829871 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; };
76 | 7555FF8C242A565B00829871 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
77 | /* End PBXFileReference section */
78 |
79 | /* Begin PBXFrameworksBuildPhase section */
80 | 376070332752C6B300CFED19 /* Frameworks */ = {
81 | isa = PBXFrameworksBuildPhase;
82 | buildActionMask = 2147483647;
83 | files = (
84 | );
85 | runOnlyForDeploymentPostprocessing = 0;
86 | };
87 | 376070412753FAC000CFED19 /* Frameworks */ = {
88 | isa = PBXFrameworksBuildPhase;
89 | buildActionMask = 2147483647;
90 | files = (
91 | );
92 | runOnlyForDeploymentPostprocessing = 0;
93 | };
94 | 7555FF78242A565900829871 /* Frameworks */ = {
95 | isa = PBXFrameworksBuildPhase;
96 | buildActionMask = 2147483647;
97 | files = (
98 | 37C3AE112788BF1A00897D2D /* FirebaseAnalyticsSwift-Beta in Frameworks */,
99 | 37C3AE132788BF1A00897D2D /* FirebaseCrashlytics in Frameworks */,
100 | );
101 | runOnlyForDeploymentPostprocessing = 0;
102 | };
103 | /* End PBXFrameworksBuildPhase section */
104 |
105 | /* Begin PBXGroup section */
106 | 375300AD27230E7C0029761B /* Scenes */ = {
107 | isa = PBXGroup;
108 | children = (
109 | 375300AE27230EA70029761B /* CatsView.swift */,
110 | 375300B1272310F80029761B /* CatsStore.swift */,
111 | 375300B3272312420029761B /* CatItem.swift */,
112 | 3769512F2725B906001B6E0D /* CatsFilter.swift */,
113 | );
114 | path = Scenes;
115 | sourceTree = "";
116 | };
117 | 375300B52723358F0029761B /* Views */ = {
118 | isa = PBXGroup;
119 | children = (
120 | 375300B6272335AD0029761B /* AsyncImage.swift */,
121 | );
122 | path = Views;
123 | sourceTree = "";
124 | };
125 | 375300B8272336480029761B /* Services */ = {
126 | isa = PBXGroup;
127 | children = (
128 | 375300B9272336540029761B /* ImageService.swift */,
129 | );
130 | path = Services;
131 | sourceTree = "";
132 | };
133 | 376070292752C48600CFED19 /* iosAppTests */ = {
134 | isa = PBXGroup;
135 | children = (
136 | 3760702A2752C48600CFED19 /* iosAppTests.swift */,
137 | 3760702C2752C48600CFED19 /* Info.plist */,
138 | );
139 | path = iosAppTests;
140 | sourceTree = "";
141 | };
142 | 376070372752C6B300CFED19 /* iosAppTests */ = {
143 | isa = PBXGroup;
144 | children = (
145 | 376070382752C6B300CFED19 /* iosAppTests.swift */,
146 | 3760703A2752C6B300CFED19 /* Info.plist */,
147 | );
148 | path = iosAppTests;
149 | sourceTree = "";
150 | };
151 | 376070452753FAC000CFED19 /* iosAppUITests */ = {
152 | isa = PBXGroup;
153 | children = (
154 | 376070462753FAC000CFED19 /* iosAppUITests.swift */,
155 | 376070482753FAC000CFED19 /* Info.plist */,
156 | );
157 | path = iosAppUITests;
158 | sourceTree = "";
159 | };
160 | 7555FF72242A565900829871 = {
161 | isa = PBXGroup;
162 | children = (
163 | 7555FF7D242A565900829871 /* iosApp */,
164 | 376070292752C48600CFED19 /* iosAppTests */,
165 | 376070372752C6B300CFED19 /* iosAppTests */,
166 | 376070452753FAC000CFED19 /* iosAppUITests */,
167 | 7555FF7C242A565900829871 /* Products */,
168 | 7555FFB0242A642200829871 /* Frameworks */,
169 | );
170 | sourceTree = "";
171 | };
172 | 7555FF7C242A565900829871 /* Products */ = {
173 | isa = PBXGroup;
174 | children = (
175 | 7555FF7B242A565900829871 /* iosApp.app */,
176 | 376070362752C6B300CFED19 /* iosAppTests.xctest */,
177 | 376070442753FAC000CFED19 /* iosAppUITests.xctest */,
178 | );
179 | name = Products;
180 | sourceTree = "";
181 | };
182 | 7555FF7D242A565900829871 /* iosApp */ = {
183 | isa = PBXGroup;
184 | children = (
185 | 375300B8272336480029761B /* Services */,
186 | 375300B52723358F0029761B /* Views */,
187 | 375300AD27230E7C0029761B /* Scenes */,
188 | 7555FF82242A565900829871 /* ContentView.swift */,
189 | 7555FF8C242A565B00829871 /* Info.plist */,
190 | 37C3AE182788C38700897D2D /* GoogleService-Info.plist */,
191 | 2152FB032600AC8F00CF470E /* iOSApp.swift */,
192 | 37C3AE142788BFF700897D2D /* AppDelegate.swift */,
193 | );
194 | path = iosApp;
195 | sourceTree = "";
196 | };
197 | 7555FFB0242A642200829871 /* Frameworks */ = {
198 | isa = PBXGroup;
199 | children = (
200 | );
201 | name = Frameworks;
202 | sourceTree = "";
203 | };
204 | /* End PBXGroup section */
205 |
206 | /* Begin PBXNativeTarget section */
207 | 376070352752C6B300CFED19 /* iosAppTests */ = {
208 | isa = PBXNativeTarget;
209 | buildConfigurationList = 3760703D2752C6B300CFED19 /* Build configuration list for PBXNativeTarget "iosAppTests" */;
210 | buildPhases = (
211 | 376070322752C6B300CFED19 /* Sources */,
212 | 376070332752C6B300CFED19 /* Frameworks */,
213 | 376070342752C6B300CFED19 /* Resources */,
214 | );
215 | buildRules = (
216 | );
217 | dependencies = (
218 | 3760703C2752C6B300CFED19 /* PBXTargetDependency */,
219 | );
220 | name = iosAppTests;
221 | productName = iosAppTests;
222 | productReference = 376070362752C6B300CFED19 /* iosAppTests.xctest */;
223 | productType = "com.apple.product-type.bundle.unit-test";
224 | };
225 | 376070432753FAC000CFED19 /* iosAppUITests */ = {
226 | isa = PBXNativeTarget;
227 | buildConfigurationList = 3760704D2753FAC000CFED19 /* Build configuration list for PBXNativeTarget "iosAppUITests" */;
228 | buildPhases = (
229 | 376070402753FAC000CFED19 /* Sources */,
230 | 376070412753FAC000CFED19 /* Frameworks */,
231 | 376070422753FAC000CFED19 /* Resources */,
232 | );
233 | buildRules = (
234 | );
235 | dependencies = (
236 | 3760704A2753FAC000CFED19 /* PBXTargetDependency */,
237 | );
238 | name = iosAppUITests;
239 | productName = iosAppUITests;
240 | productReference = 376070442753FAC000CFED19 /* iosAppUITests.xctest */;
241 | productType = "com.apple.product-type.bundle.ui-testing";
242 | };
243 | 7555FF7A242A565900829871 /* iosApp */ = {
244 | isa = PBXNativeTarget;
245 | buildConfigurationList = 7555FFA5242A565B00829871 /* Build configuration list for PBXNativeTarget "iosApp" */;
246 | buildPhases = (
247 | 7555FFB5242A651A00829871 /* Run Script */,
248 | 7555FF77242A565900829871 /* Sources */,
249 | 7555FF78242A565900829871 /* Frameworks */,
250 | 7555FF79242A565900829871 /* Resources */,
251 | 7555FFB4242A642300829871 /* Embed Frameworks */,
252 | 37C3AE1A2788C4F000897D2D /* Set up Xcode to automatically upload dSYM files */,
253 | );
254 | buildRules = (
255 | );
256 | dependencies = (
257 | );
258 | name = iosApp;
259 | packageProductDependencies = (
260 | 37C3AE102788BF1A00897D2D /* FirebaseAnalyticsSwift-Beta */,
261 | 37C3AE122788BF1A00897D2D /* FirebaseCrashlytics */,
262 | );
263 | productName = iosApp;
264 | productReference = 7555FF7B242A565900829871 /* iosApp.app */;
265 | productType = "com.apple.product-type.application";
266 | };
267 | /* End PBXNativeTarget section */
268 |
269 | /* Begin PBXProject section */
270 | 7555FF73242A565900829871 /* Project object */ = {
271 | isa = PBXProject;
272 | attributes = {
273 | LastSwiftUpdateCheck = 1250;
274 | LastUpgradeCheck = 1130;
275 | ORGANIZATIONNAME = orgName;
276 | TargetAttributes = {
277 | 376070352752C6B300CFED19 = {
278 | CreatedOnToolsVersion = 12.5.1;
279 | TestTargetID = 7555FF7A242A565900829871;
280 | };
281 | 376070432753FAC000CFED19 = {
282 | CreatedOnToolsVersion = 12.5.1;
283 | TestTargetID = 7555FF7A242A565900829871;
284 | };
285 | 7555FF7A242A565900829871 = {
286 | CreatedOnToolsVersion = 11.3.1;
287 | };
288 | };
289 | };
290 | buildConfigurationList = 7555FF76242A565900829871 /* Build configuration list for PBXProject "iosApp" */;
291 | compatibilityVersion = "Xcode 9.3";
292 | developmentRegion = en;
293 | hasScannedForEncodings = 0;
294 | knownRegions = (
295 | en,
296 | Base,
297 | );
298 | mainGroup = 7555FF72242A565900829871;
299 | packageReferences = (
300 | 37C3AE0F2788BF1A00897D2D /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */,
301 | );
302 | productRefGroup = 7555FF7C242A565900829871 /* Products */;
303 | projectDirPath = "";
304 | projectRoot = "";
305 | targets = (
306 | 7555FF7A242A565900829871 /* iosApp */,
307 | 376070352752C6B300CFED19 /* iosAppTests */,
308 | 376070432753FAC000CFED19 /* iosAppUITests */,
309 | );
310 | };
311 | /* End PBXProject section */
312 |
313 | /* Begin PBXResourcesBuildPhase section */
314 | 376070342752C6B300CFED19 /* Resources */ = {
315 | isa = PBXResourcesBuildPhase;
316 | buildActionMask = 2147483647;
317 | files = (
318 | );
319 | runOnlyForDeploymentPostprocessing = 0;
320 | };
321 | 376070422753FAC000CFED19 /* Resources */ = {
322 | isa = PBXResourcesBuildPhase;
323 | buildActionMask = 2147483647;
324 | files = (
325 | );
326 | runOnlyForDeploymentPostprocessing = 0;
327 | };
328 | 7555FF79242A565900829871 /* Resources */ = {
329 | isa = PBXResourcesBuildPhase;
330 | buildActionMask = 2147483647;
331 | files = (
332 | 37C3AE192788C38700897D2D /* GoogleService-Info.plist in Resources */,
333 | );
334 | runOnlyForDeploymentPostprocessing = 0;
335 | };
336 | /* End PBXResourcesBuildPhase section */
337 |
338 | /* Begin PBXShellScriptBuildPhase section */
339 | 37C3AE1A2788C4F000897D2D /* Set up Xcode to automatically upload dSYM files */ = {
340 | isa = PBXShellScriptBuildPhase;
341 | buildActionMask = 2147483647;
342 | files = (
343 | );
344 | inputFileListPaths = (
345 | );
346 | inputPaths = (
347 | "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}",
348 | "$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)",
349 | );
350 | name = "Set up Xcode to automatically upload dSYM files";
351 | outputFileListPaths = (
352 | );
353 | outputPaths = (
354 | );
355 | runOnlyForDeploymentPostprocessing = 0;
356 | shellPath = /bin/sh;
357 | shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n\"${BUILD_DIR%/Build/*}/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/run\"\n";
358 | };
359 | 7555FFB5242A651A00829871 /* Run Script */ = {
360 | isa = PBXShellScriptBuildPhase;
361 | buildActionMask = 2147483647;
362 | files = (
363 | );
364 | inputFileListPaths = (
365 | );
366 | inputPaths = (
367 | );
368 | name = "Run Script";
369 | outputFileListPaths = (
370 | );
371 | outputPaths = (
372 | );
373 | runOnlyForDeploymentPostprocessing = 0;
374 | shellPath = /bin/sh;
375 | shellScript = "cd \"$SRCROOT/..\"\n./gradlew :shared:embedAndSignAppleFrameworkForXcode\n";
376 | };
377 | /* End PBXShellScriptBuildPhase section */
378 |
379 | /* Begin PBXSourcesBuildPhase section */
380 | 376070322752C6B300CFED19 /* Sources */ = {
381 | isa = PBXSourcesBuildPhase;
382 | buildActionMask = 2147483647;
383 | files = (
384 | 376070392752C6B300CFED19 /* iosAppTests.swift in Sources */,
385 | );
386 | runOnlyForDeploymentPostprocessing = 0;
387 | };
388 | 376070402753FAC000CFED19 /* Sources */ = {
389 | isa = PBXSourcesBuildPhase;
390 | buildActionMask = 2147483647;
391 | files = (
392 | 376070472753FAC000CFED19 /* iosAppUITests.swift in Sources */,
393 | );
394 | runOnlyForDeploymentPostprocessing = 0;
395 | };
396 | 7555FF77242A565900829871 /* Sources */ = {
397 | isa = PBXSourcesBuildPhase;
398 | buildActionMask = 2147483647;
399 | files = (
400 | 375300AF27230EA70029761B /* CatsView.swift in Sources */,
401 | 2152FB042600AC8F00CF470E /* iOSApp.swift in Sources */,
402 | 375300B4272312420029761B /* CatItem.swift in Sources */,
403 | 37C3AE152788BFF700897D2D /* AppDelegate.swift in Sources */,
404 | 375300B2272310F80029761B /* CatsStore.swift in Sources */,
405 | 376951302725B906001B6E0D /* CatsFilter.swift in Sources */,
406 | 375300B7272335AD0029761B /* AsyncImage.swift in Sources */,
407 | 7555FF83242A565900829871 /* ContentView.swift in Sources */,
408 | 375300BA272336540029761B /* ImageService.swift in Sources */,
409 | );
410 | runOnlyForDeploymentPostprocessing = 0;
411 | };
412 | /* End PBXSourcesBuildPhase section */
413 |
414 | /* Begin PBXTargetDependency section */
415 | 3760703C2752C6B300CFED19 /* PBXTargetDependency */ = {
416 | isa = PBXTargetDependency;
417 | target = 7555FF7A242A565900829871 /* iosApp */;
418 | targetProxy = 3760703B2752C6B300CFED19 /* PBXContainerItemProxy */;
419 | };
420 | 3760704A2753FAC000CFED19 /* PBXTargetDependency */ = {
421 | isa = PBXTargetDependency;
422 | target = 7555FF7A242A565900829871 /* iosApp */;
423 | targetProxy = 376070492753FAC000CFED19 /* PBXContainerItemProxy */;
424 | };
425 | /* End PBXTargetDependency section */
426 |
427 | /* Begin XCBuildConfiguration section */
428 | 3760703E2752C6B300CFED19 /* Debug */ = {
429 | isa = XCBuildConfiguration;
430 | buildSettings = {
431 | BUNDLE_LOADER = "$(TEST_HOST)";
432 | CODE_SIGN_STYLE = Automatic;
433 | DEBUG_INFORMATION_FORMAT = dwarf;
434 | INFOPLIST_FILE = iosAppTests/Info.plist;
435 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
436 | LD_RUNPATH_SEARCH_PATHS = (
437 | "$(inherited)",
438 | "@executable_path/Frameworks",
439 | "@loader_path/Frameworks",
440 | );
441 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosAppTests;
442 | PRODUCT_NAME = "$(TARGET_NAME)";
443 | SWIFT_VERSION = 5.0;
444 | TARGETED_DEVICE_FAMILY = "1,2";
445 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iosApp.app/iosApp";
446 | };
447 | name = Debug;
448 | };
449 | 3760703F2752C6B300CFED19 /* Release */ = {
450 | isa = XCBuildConfiguration;
451 | buildSettings = {
452 | BUNDLE_LOADER = "$(TEST_HOST)";
453 | CODE_SIGN_STYLE = Automatic;
454 | INFOPLIST_FILE = iosAppTests/Info.plist;
455 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
456 | LD_RUNPATH_SEARCH_PATHS = (
457 | "$(inherited)",
458 | "@executable_path/Frameworks",
459 | "@loader_path/Frameworks",
460 | );
461 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosAppTests;
462 | PRODUCT_NAME = "$(TARGET_NAME)";
463 | SWIFT_VERSION = 5.0;
464 | TARGETED_DEVICE_FAMILY = "1,2";
465 | TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iosApp.app/iosApp";
466 | };
467 | name = Release;
468 | };
469 | 3760704B2753FAC000CFED19 /* Debug */ = {
470 | isa = XCBuildConfiguration;
471 | buildSettings = {
472 | CODE_SIGN_STYLE = Automatic;
473 | DEBUG_INFORMATION_FORMAT = dwarf;
474 | INFOPLIST_FILE = iosAppUITests/Info.plist;
475 | IPHONEOS_DEPLOYMENT_TARGET = 14.5;
476 | LD_RUNPATH_SEARCH_PATHS = (
477 | "$(inherited)",
478 | "@executable_path/Frameworks",
479 | "@loader_path/Frameworks",
480 | );
481 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosAppUITests;
482 | PRODUCT_NAME = "$(TARGET_NAME)";
483 | SWIFT_VERSION = 5.0;
484 | TARGETED_DEVICE_FAMILY = "1,2";
485 | TEST_TARGET_NAME = iosApp;
486 | };
487 | name = Debug;
488 | };
489 | 3760704C2753FAC000CFED19 /* Release */ = {
490 | isa = XCBuildConfiguration;
491 | buildSettings = {
492 | CODE_SIGN_STYLE = Automatic;
493 | INFOPLIST_FILE = iosAppUITests/Info.plist;
494 | IPHONEOS_DEPLOYMENT_TARGET = 14.5;
495 | LD_RUNPATH_SEARCH_PATHS = (
496 | "$(inherited)",
497 | "@executable_path/Frameworks",
498 | "@loader_path/Frameworks",
499 | );
500 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosAppUITests;
501 | PRODUCT_NAME = "$(TARGET_NAME)";
502 | SWIFT_VERSION = 5.0;
503 | TARGETED_DEVICE_FAMILY = "1,2";
504 | TEST_TARGET_NAME = iosApp;
505 | };
506 | name = Release;
507 | };
508 | 7555FFA3242A565B00829871 /* Debug */ = {
509 | isa = XCBuildConfiguration;
510 | buildSettings = {
511 | ALWAYS_SEARCH_USER_PATHS = NO;
512 | CLANG_ANALYZER_NONNULL = YES;
513 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
514 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
515 | CLANG_CXX_LIBRARY = "libc++";
516 | CLANG_ENABLE_MODULES = YES;
517 | CLANG_ENABLE_OBJC_ARC = YES;
518 | CLANG_ENABLE_OBJC_WEAK = YES;
519 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
520 | CLANG_WARN_BOOL_CONVERSION = YES;
521 | CLANG_WARN_COMMA = YES;
522 | CLANG_WARN_CONSTANT_CONVERSION = YES;
523 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
524 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
525 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
526 | CLANG_WARN_EMPTY_BODY = YES;
527 | CLANG_WARN_ENUM_CONVERSION = YES;
528 | CLANG_WARN_INFINITE_RECURSION = YES;
529 | CLANG_WARN_INT_CONVERSION = YES;
530 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
531 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
532 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
533 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
534 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
535 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
536 | CLANG_WARN_STRICT_PROTOTYPES = YES;
537 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
538 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
539 | CLANG_WARN_UNREACHABLE_CODE = YES;
540 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
541 | COPY_PHASE_STRIP = NO;
542 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
543 | ENABLE_STRICT_OBJC_MSGSEND = YES;
544 | ENABLE_TESTABILITY = YES;
545 | GCC_C_LANGUAGE_STANDARD = gnu11;
546 | GCC_DYNAMIC_NO_PIC = NO;
547 | GCC_NO_COMMON_BLOCKS = YES;
548 | GCC_OPTIMIZATION_LEVEL = 0;
549 | GCC_PREPROCESSOR_DEFINITIONS = (
550 | "DEBUG=1",
551 | "$(inherited)",
552 | );
553 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
554 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
555 | GCC_WARN_UNDECLARED_SELECTOR = YES;
556 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
557 | GCC_WARN_UNUSED_FUNCTION = YES;
558 | GCC_WARN_UNUSED_VARIABLE = YES;
559 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
560 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
561 | MTL_FAST_MATH = YES;
562 | ONLY_ACTIVE_ARCH = YES;
563 | SDKROOT = iphoneos;
564 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
565 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
566 | };
567 | name = Debug;
568 | };
569 | 7555FFA4242A565B00829871 /* Release */ = {
570 | isa = XCBuildConfiguration;
571 | buildSettings = {
572 | ALWAYS_SEARCH_USER_PATHS = NO;
573 | CLANG_ANALYZER_NONNULL = YES;
574 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
575 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
576 | CLANG_CXX_LIBRARY = "libc++";
577 | CLANG_ENABLE_MODULES = YES;
578 | CLANG_ENABLE_OBJC_ARC = YES;
579 | CLANG_ENABLE_OBJC_WEAK = YES;
580 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
581 | CLANG_WARN_BOOL_CONVERSION = YES;
582 | CLANG_WARN_COMMA = YES;
583 | CLANG_WARN_CONSTANT_CONVERSION = YES;
584 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
585 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
586 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
587 | CLANG_WARN_EMPTY_BODY = YES;
588 | CLANG_WARN_ENUM_CONVERSION = YES;
589 | CLANG_WARN_INFINITE_RECURSION = YES;
590 | CLANG_WARN_INT_CONVERSION = YES;
591 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
592 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
593 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
594 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
595 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
596 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
597 | CLANG_WARN_STRICT_PROTOTYPES = YES;
598 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
599 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
600 | CLANG_WARN_UNREACHABLE_CODE = YES;
601 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
602 | COPY_PHASE_STRIP = NO;
603 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
604 | ENABLE_NS_ASSERTIONS = NO;
605 | ENABLE_STRICT_OBJC_MSGSEND = YES;
606 | GCC_C_LANGUAGE_STANDARD = gnu11;
607 | GCC_NO_COMMON_BLOCKS = YES;
608 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
609 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
610 | GCC_WARN_UNDECLARED_SELECTOR = YES;
611 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
612 | GCC_WARN_UNUSED_FUNCTION = YES;
613 | GCC_WARN_UNUSED_VARIABLE = YES;
614 | IPHONEOS_DEPLOYMENT_TARGET = 14.1;
615 | MTL_ENABLE_DEBUG_INFO = NO;
616 | MTL_FAST_MATH = YES;
617 | SDKROOT = iphoneos;
618 | SWIFT_COMPILATION_MODE = wholemodule;
619 | SWIFT_OPTIMIZATION_LEVEL = "-O";
620 | VALIDATE_PRODUCT = YES;
621 | };
622 | name = Release;
623 | };
624 | 7555FFA6242A565B00829871 /* Debug */ = {
625 | isa = XCBuildConfiguration;
626 | buildSettings = {
627 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
628 | CODE_SIGN_STYLE = Automatic;
629 | ENABLE_PREVIEWS = YES;
630 | FRAMEWORK_SEARCH_PATHS = "$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)";
631 | INFOPLIST_FILE = iosApp/Info.plist;
632 | LD_RUNPATH_SEARCH_PATHS = (
633 | "$(inherited)",
634 | "@executable_path/Frameworks",
635 | );
636 | OTHER_LDFLAGS = (
637 | "$(inherited)",
638 | "-framework",
639 | shared,
640 | );
641 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosApp;
642 | PRODUCT_NAME = "$(TARGET_NAME)";
643 | SWIFT_VERSION = 5.0;
644 | TARGETED_DEVICE_FAMILY = "1,2";
645 | };
646 | name = Debug;
647 | };
648 | 7555FFA7242A565B00829871 /* Release */ = {
649 | isa = XCBuildConfiguration;
650 | buildSettings = {
651 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
652 | CODE_SIGN_STYLE = Automatic;
653 | ENABLE_PREVIEWS = YES;
654 | FRAMEWORK_SEARCH_PATHS = "$(SRCROOT)/../shared/build/xcode-frameworks/$(CONFIGURATION)/$(SDK_NAME)";
655 | INFOPLIST_FILE = iosApp/Info.plist;
656 | LD_RUNPATH_SEARCH_PATHS = (
657 | "$(inherited)",
658 | "@executable_path/Frameworks",
659 | );
660 | OTHER_LDFLAGS = (
661 | "$(inherited)",
662 | "-framework",
663 | shared,
664 | );
665 | PRODUCT_BUNDLE_IDENTIFIER = eu.rajniak.cat.iosApp;
666 | PRODUCT_NAME = "$(TARGET_NAME)";
667 | SWIFT_VERSION = 5.0;
668 | TARGETED_DEVICE_FAMILY = "1,2";
669 | };
670 | name = Release;
671 | };
672 | /* End XCBuildConfiguration section */
673 |
674 | /* Begin XCConfigurationList section */
675 | 3760703D2752C6B300CFED19 /* Build configuration list for PBXNativeTarget "iosAppTests" */ = {
676 | isa = XCConfigurationList;
677 | buildConfigurations = (
678 | 3760703E2752C6B300CFED19 /* Debug */,
679 | 3760703F2752C6B300CFED19 /* Release */,
680 | );
681 | defaultConfigurationIsVisible = 0;
682 | defaultConfigurationName = Debug;
683 | };
684 | 3760704D2753FAC000CFED19 /* Build configuration list for PBXNativeTarget "iosAppUITests" */ = {
685 | isa = XCConfigurationList;
686 | buildConfigurations = (
687 | 3760704B2753FAC000CFED19 /* Debug */,
688 | 3760704C2753FAC000CFED19 /* Release */,
689 | );
690 | defaultConfigurationIsVisible = 0;
691 | defaultConfigurationName = Debug;
692 | };
693 | 7555FF76242A565900829871 /* Build configuration list for PBXProject "iosApp" */ = {
694 | isa = XCConfigurationList;
695 | buildConfigurations = (
696 | 7555FFA3242A565B00829871 /* Debug */,
697 | 7555FFA4242A565B00829871 /* Release */,
698 | );
699 | defaultConfigurationIsVisible = 0;
700 | defaultConfigurationName = Debug;
701 | };
702 | 7555FFA5242A565B00829871 /* Build configuration list for PBXNativeTarget "iosApp" */ = {
703 | isa = XCConfigurationList;
704 | buildConfigurations = (
705 | 7555FFA6242A565B00829871 /* Debug */,
706 | 7555FFA7242A565B00829871 /* Release */,
707 | );
708 | defaultConfigurationIsVisible = 0;
709 | defaultConfigurationName = Debug;
710 | };
711 | /* End XCConfigurationList section */
712 |
713 | /* Begin XCRemoteSwiftPackageReference section */
714 | 37C3AE0F2788BF1A00897D2D /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */ = {
715 | isa = XCRemoteSwiftPackageReference;
716 | repositoryURL = "https://github.com/firebase/firebase-ios-sdk";
717 | requirement = {
718 | kind = upToNextMajorVersion;
719 | minimumVersion = 8.0.0;
720 | };
721 | };
722 | /* End XCRemoteSwiftPackageReference section */
723 |
724 | /* Begin XCSwiftPackageProductDependency section */
725 | 37C3AE102788BF1A00897D2D /* FirebaseAnalyticsSwift-Beta */ = {
726 | isa = XCSwiftPackageProductDependency;
727 | package = 37C3AE0F2788BF1A00897D2D /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
728 | productName = "FirebaseAnalyticsSwift-Beta";
729 | };
730 | 37C3AE122788BF1A00897D2D /* FirebaseCrashlytics */ = {
731 | isa = XCSwiftPackageProductDependency;
732 | package = 37C3AE0F2788BF1A00897D2D /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */;
733 | productName = FirebaseCrashlytics;
734 | };
735 | /* End XCSwiftPackageProductDependency section */
736 | };
737 | rootObject = 7555FF73242A565900829871 /* Project object */;
738 | }
739 |
--------------------------------------------------------------------------------
/iosApp/iosApp/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import Firebase
3 |
4 | class AppDelegate: NSObject, UIApplicationDelegate {
5 | func application(
6 | _ application: UIApplication,
7 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
8 | ) -> Bool {
9 | FirebaseApp.configure()
10 | return true
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/iosApp/iosApp/ContentView.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 | import shared
3 |
4 | struct ContentView: View {
5 |
6 | var body: some View {
7 | CatsView()
8 | }
9 | }
10 |
11 | struct ContentView_Previews: PreviewProvider {
12 | static var previews: some View {
13 | ContentView()
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/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 | UIApplicationSceneManifest
24 |
25 | UIApplicationSupportsMultipleScenes
26 |
27 |
28 | UILaunchScreen
29 |
30 | UIRequiredDeviceCapabilities
31 |
32 | armv7
33 |
34 | UISupportedInterfaceOrientations
35 |
36 | UIInterfaceOrientationPortrait
37 | UIInterfaceOrientationLandscapeLeft
38 | UIInterfaceOrientationLandscapeRight
39 |
40 | UISupportedInterfaceOrientations~ipad
41 |
42 | UIInterfaceOrientationPortrait
43 | UIInterfaceOrientationPortraitUpsideDown
44 | UIInterfaceOrientationLandscapeLeft
45 | UIInterfaceOrientationLandscapeRight
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Scenes/CatItem.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 | import shared
3 |
4 | struct CatItem: View {
5 | let cat: Cat
6 |
7 | var body: some View {
8 | VStack {
9 | AsyncImage(
10 | ImageService.shared.getImage(url: cat.url)
11 | ) { image in
12 | image.resizable()
13 | }
14 | .frame(width: 96, height: 96)
15 | }
16 | }
17 | }
18 |
19 | struct CatItem_Previews: PreviewProvider {
20 | static var previews: some View {
21 | CatItem(cat: FakeData.shared.cats[0])
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Scenes/CatsFilter.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 |
3 | struct CatsFilter: View {
4 | @Environment(\.presentationMode) var presentationMode
5 |
6 | @StateObject var store: CatsStore
7 |
8 | var body: some View {
9 | ZStack {
10 | VStack(
11 | alignment: .leading,
12 | spacing: 32
13 |
14 | ) {
15 | List {
16 | Text("Categories")
17 |
18 | ForEach(store.categories.indices, id: \.self) { index in
19 | Toggle(isOn: $store.categories[index].enabled) {
20 | Text(store.categories[index].name)
21 | }
22 | .onChange(of: store.categories[index].enabled, perform: { checked in
23 | store.onCategoryChecked(
24 | categoryId: store.categories[index].id,
25 | checked: checked
26 | )
27 | })
28 | }
29 |
30 | Spacer()
31 |
32 | Text("MimeTypes")
33 |
34 | ForEach(store.mimeTypes.indices, id: \.self) { index in
35 | Toggle(isOn: $store.mimeTypes[index].enabled) {
36 | Text(store.mimeTypes[index].name)
37 | }
38 | .onChange(of: store.mimeTypes[index].enabled, perform: { checked in
39 | store.onMimeTypeChecked(
40 | mimeTypeId: store.mimeTypes[index].id,
41 | checked: checked
42 | )
43 | })
44 | }
45 | }
46 | }
47 | .navigationTitle("Filter")
48 | .toolbar {
49 | ToolbarItem(placement: .navigationBarTrailing) {
50 | Button(action: close) {
51 | Image(systemName: "checkmark")
52 | }
53 | }
54 | }
55 | }
56 | }
57 | }
58 |
59 | extension CatsFilter {
60 | func close() {
61 | presentationMode.wrappedValue.dismiss()
62 | }
63 | }
64 |
65 | struct CatsFilter_Previews: PreviewProvider {
66 | static var previews: some View {
67 | CatsFilter(store: CatsStore())
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Scenes/CatsStore.swift:
--------------------------------------------------------------------------------
1 | import Combine
2 | import shared
3 |
4 | class CatsStore: ObservableObject {
5 | // FIXME: how to support empty constructor with default value (Like in Kotlin)
6 | private let viewModel = CatsViewModel(
7 | catsStore: CatViewerServiceLocator.shared.catsStore,
8 | dispatcher: CatViewerServiceLocator.shared.defaultDispatcher
9 | )
10 |
11 | @Published var cats: [Cat] = []
12 | @Published var hasNextPage: Bool = false
13 |
14 | @Published var categories: [CategoryModel] = []
15 | @Published var mimeTypes: [MimeTypeModel] = []
16 |
17 | func start() {
18 | LoggerKt.withTag(tag: "CatsStore").i {"start"}
19 |
20 | viewModel.cats.watch { cats in
21 | guard let list = cats?.compactMap({ $0 as? Cat}) else {
22 | return
23 | }
24 | self.cats = list
25 | self.hasNextPage = true // FIXME: should check if there is more data
26 | }
27 |
28 | viewModel.categories.watch { categories in
29 | guard let list = categories?.compactMap({ $0 as? CategoryModel}) else {
30 | return
31 | }
32 | self.categories = list
33 | }
34 |
35 | viewModel.mimeTypes.watch { categories in
36 | guard let list = categories?.compactMap({ $0 as? MimeTypeModel}) else {
37 | return
38 | }
39 | self.mimeTypes = list
40 | }
41 | }
42 |
43 | func onScrolledToTheEnd() {
44 | viewModel.onScrolledToTheEnd()
45 | }
46 |
47 | func onCategoryChecked(categoryId: Int32, checked: Bool) {
48 | viewModel.onCategoryChecked(categoryId: categoryId, checked: checked)
49 | }
50 |
51 | func onMimeTypeChecked(mimeTypeId: Int32, checked: Bool) {
52 | viewModel.onMimeTypeChecked(mimeTypeId: mimeTypeId, checked: checked)
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Scenes/CatsView.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 |
3 | struct CatsView: View {
4 | @StateObject var store = CatsStore()
5 |
6 | @State var isFilterPresented = false
7 |
8 | var columns: [GridItem] =
9 | [.init(.adaptive(minimum: 96, maximum: 128))]
10 |
11 | var body: some View {
12 | NavigationView {
13 | VStack(spacing: 32) {
14 | ScrollView {
15 | LazyVGrid(columns: columns, spacing: 2) {
16 | ForEach(store.cats, id: \.id) { cat in
17 | CatItem(cat: cat)
18 | }
19 | if (store.hasNextPage) {
20 | loadingItem
21 | }
22 | }
23 | .padding(.horizontal, 16)
24 | }
25 | }
26 | .onAppear {
27 | store.start()
28 | }
29 | .navigationTitle("Cat Viewer Demo")
30 | .toolbar {
31 | ToolbarItem(placement: .primaryAction) {
32 | Button(action: {
33 | isFilterPresented = true
34 | }, label: {
35 | Image(systemName: "slider.horizontal.3")
36 | })
37 | }
38 | }
39 | .sheet(isPresented: $isFilterPresented, onDismiss: handleFilterChange) {
40 | NavigationView {
41 | CatsFilter(store: store)
42 | }
43 | }
44 | }
45 | }
46 |
47 | private var loadingItem: some View {
48 | VStack {
49 | ProgressView()
50 | }
51 | .frame(width: 96, height: 96)
52 | .onAppear(perform: {
53 | store.onScrolledToTheEnd()
54 | })
55 | }
56 |
57 | func handleFilterChange() {
58 |
59 | }
60 | }
61 |
62 | struct CatsView_Previews: PreviewProvider {
63 | static var previews: some View {
64 | CatsView()
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Services/ImageService.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 | import Combine
3 | import Foundation
4 |
5 | class ImageService {
6 | static let shared = ImageService()
7 |
8 | private init() {
9 | // Singleton
10 | }
11 | }
12 |
13 | extension ImageService {
14 | func getImage(url: String) -> AnyPublisher {
15 | guard let url = URL(string: url) else {
16 | return AnyPublisher(
17 | Fail(error: URLError(.badURL))
18 | )
19 | }
20 |
21 | return URLSession.shared
22 | .dataTaskPublisher(for: url)
23 | .tryMap { result -> UIImage in
24 | return UIImage(data: result.data) ?? UIImage()
25 | }
26 | .eraseToAnyPublisher()
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/iosApp/iosApp/Views/AsyncImage.swift:
--------------------------------------------------------------------------------
1 | import Combine
2 | import SwiftUI
3 |
4 | struct AsyncImage: View {
5 | @StateObject private var store: AsyncImageStore
6 |
7 | private let content: (Image) -> Content
8 |
9 | init(
10 | _ imagePublisher: AnyPublisher,
11 | @ViewBuilder content: @escaping (Image) -> Content
12 | ) {
13 | self.content = content
14 |
15 | _store = .init(
16 | wrappedValue: AsyncImageStore(imagePublisher: imagePublisher)
17 | )
18 | }
19 |
20 | var body: some View {
21 | VStack {
22 | if let image = store.image {
23 | content(
24 | Image(uiImage: image)
25 | )
26 | } else {
27 | ProgressView()
28 | }
29 | }
30 | .onAppear(perform: store.load)
31 | }
32 | }
33 |
34 | class AsyncImageStore: ObservableObject {
35 | @Published var image: UIImage?
36 |
37 | private let imagePublisher: AnyPublisher
38 |
39 | private var cancellable: AnyCancellable?
40 |
41 | init(imagePublisher: AnyPublisher) {
42 | self.imagePublisher = imagePublisher
43 | }
44 |
45 | func load() {
46 | cancellable = imagePublisher
47 | .map { $0 }
48 | .replaceError(with: nil)
49 | .receive(on: DispatchQueue.main)
50 | .assign(to: \.image, on: self)
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/iosApp/iosApp/iOSApp.swift:
--------------------------------------------------------------------------------
1 | import SwiftUI
2 |
3 | @main
4 | struct iOSApp: App {
5 | @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
6 |
7 | var body: some Scene {
8 | WindowGroup {
9 | ContentView()
10 | }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/iosApp/iosAppTests/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 |
22 |
23 |
--------------------------------------------------------------------------------
/iosApp/iosAppTests/iosAppTests.swift:
--------------------------------------------------------------------------------
1 | import XCTest
2 |
3 | class iosAppTests: XCTestCase {
4 |
5 | override func setUpWithError() throws {
6 | // Put setup code here. This method is called before the invocation of each test method in the class.
7 | }
8 |
9 | override func tearDownWithError() throws {
10 | // Put teardown code here. This method is called after the invocation of each test method in the class.
11 | }
12 |
13 | func testExample() throws {
14 | // This is an example of a functional test case.
15 | // Use XCTAssert and related functions to verify your tests produce the correct results.
16 | }
17 |
18 | func testPerformanceExample() throws {
19 | // This is an example of a performance test case.
20 | measure {
21 | // Put the code you want to measure the time of here.
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/iosApp/iosAppUITests/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 |
22 |
23 |
--------------------------------------------------------------------------------
/iosApp/iosAppUITests/iosAppUITests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // iosAppUITests.swift
3 | // iosAppUITests
4 | //
5 | // Created by Martin Rajniak on 28/11/2021.
6 | // Copyright © 2021 orgName. All rights reserved.
7 | //
8 |
9 | import XCTest
10 |
11 | class iosAppUITests: XCTestCase {
12 |
13 | override func setUpWithError() throws {
14 | // Put setup code here. This method is called before the invocation of each test method in the class.
15 |
16 | // In UI tests it is usually best to stop immediately when a failure occurs.
17 | continueAfterFailure = false
18 |
19 | // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
20 | }
21 |
22 | override func tearDownWithError() throws {
23 | // Put teardown code here. This method is called after the invocation of each test method in the class.
24 | }
25 |
26 | func testExample() throws {
27 | // UI tests must launch the application that they test.
28 | let app = XCUIApplication()
29 | app.launch()
30 |
31 | // Use recording to get started writing UI tests.
32 | // Use XCTAssert and related functions to verify your tests produce the correct results.
33 | }
34 |
35 | func testLaunchPerformance() throws {
36 | if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
37 | // This measures how long it takes to launch your application.
38 | measure(metrics: [XCTApplicationLaunchMetric()]) {
39 | XCUIApplication().launch()
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/readme/android_demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/readme/android_demo.gif
--------------------------------------------------------------------------------
/readme/ios_demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MartinRajniak/CatViewerDemo/43e71afc3cd9ed4a652c1c1108a43c12fc295423/readme/ios_demo.gif
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
2 |
3 | pluginManagement {
4 | repositories {
5 | google()
6 | gradlePluginPortal()
7 | mavenCentral()
8 | }
9 | }
10 |
11 | include(":androidApp")
12 | include(":shared")
--------------------------------------------------------------------------------
/shared/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING
2 | import org.jetbrains.kotlin.gradle.plugin.mpp.Framework
3 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
4 |
5 | plugins {
6 | alias(libs.plugins.android.library)
7 | alias(libs.plugins.buildkonfig)
8 | alias(libs.plugins.kotlin.multiplatform)
9 | alias(libs.plugins.kotlin.serialization)
10 | }
11 |
12 | kotlin {
13 | android()
14 |
15 | val iosTarget: (String, KotlinNativeTarget.() -> Unit) -> KotlinNativeTarget = when {
16 | System.getenv("SDK_NAME")?.startsWith("iphoneos") == true -> ::iosArm64
17 | System.getenv("NATIVE_ARCH")?.startsWith("arm") == true -> ::iosSimulatorArm64
18 | else -> ::iosX64
19 | }
20 |
21 | iosTarget("ios") {
22 | binaries {
23 | framework {
24 | baseName = "shared"
25 | }
26 | }
27 | }
28 |
29 | sourceSets {
30 | val commonMain by getting {
31 | dependencies {
32 | implementation(libs.kotlinx.coroutines.core)
33 |
34 | implementation(libs.uuid)
35 |
36 | implementation(libs.ktor.client.core)
37 | implementation(libs.ktor.client.content.negotiation)
38 | implementation(libs.ktor.serialization.kotlinx.json)
39 |
40 | implementation(libs.multiplatform.settings.coroutines)
41 |
42 | // Using api to export Kermit to iOS
43 | api(libs.kermit)
44 | api(libs.kermit.crashlytics)
45 | }
46 | }
47 | val commonTest by getting {
48 | dependencies {
49 | // TODO: might want to use JUnit with AssertJ instead (https://stackoverflow.com/a/63427057)
50 | implementation(libs.kotlin.test.common)
51 | implementation(libs.kotlin.test.annotations.common)
52 |
53 | implementation(libs.kotlinx.coroutines.test)
54 |
55 | implementation(libs.multiplatform.settings.test)
56 |
57 | implementation(libs.kermit.test)
58 | }
59 | }
60 | val androidMain by getting {
61 | dependencies {
62 | implementation(libs.androidx.lifecycle.viewmodel)
63 |
64 | implementation(libs.ktor.client.android)
65 |
66 | implementation(libs.androidx.datastore.preferences)
67 | implementation(libs.androidx.startup.runtime)
68 | }
69 | }
70 | val androidTest by getting {
71 | dependencies {
72 | implementation(libs.kotlin.test.junit)
73 | implementation(libs.junit)
74 | }
75 | }
76 | val iosMain by getting {
77 | dependencies {
78 | implementation(libs.ktor.client.ios)
79 | }
80 | }
81 | val iosTest by getting
82 | }
83 |
84 | // To make kermit available in iOS project - increases binary size because of the extra headers.
85 | // More info: https://github.com/touchlab/Kermit/blob/main/samples/sample-swift-export/README.md
86 | targets.withType {
87 | binaries.withType {
88 | export(libs.kermit)
89 | }
90 | }
91 | }
92 |
93 | android {
94 | compileSdkVersion(31)
95 | sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
96 | defaultConfig {
97 | minSdkVersion(23)
98 | targetSdkVersion(30)
99 | }
100 | }
101 |
102 | buildkonfig {
103 | packageName = "eu.rajniak.cat"
104 |
105 | defaultConfigs {
106 | buildConfigField(
107 | type = STRING,
108 | name = "api_key",
109 | value = findProperty("catsApiKey") as? String ?: throw Exception("catsApiKey is not set")
110 | )
111 | }
112 | }
113 |
114 | tasks.withType {
115 | kotlinOptions.jvmTarget = "1.8"
116 | kotlinOptions.freeCompilerArgs += "-Xjvm-default=all"
117 | }
118 |
--------------------------------------------------------------------------------
/shared/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
12 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/shared/src/androidMain/kotlin/eu/rajniak/cat/utils/AtomicInt.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import java.util.concurrent.atomic.AtomicInteger
4 |
5 | actual typealias AtomicInt = AtomicInteger
6 |
--------------------------------------------------------------------------------
/shared/src/androidMain/kotlin/eu/rajniak/cat/utils/AtomicReference.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import java.util.concurrent.atomic.AtomicReference
4 |
5 | actual typealias AtomicReference = AtomicReference
6 |
--------------------------------------------------------------------------------
/shared/src/androidMain/kotlin/eu/rajniak/cat/utils/DataStoreSettings.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2020 Russell Wolf
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package eu.rajniak.cat.utils
18 |
19 | import androidx.datastore.core.DataStore
20 | import androidx.datastore.preferences.core.Preferences
21 | import androidx.datastore.preferences.core.booleanPreferencesKey
22 | import androidx.datastore.preferences.core.doublePreferencesKey
23 | import androidx.datastore.preferences.core.edit
24 | import androidx.datastore.preferences.core.floatPreferencesKey
25 | import androidx.datastore.preferences.core.intPreferencesKey
26 | import androidx.datastore.preferences.core.longPreferencesKey
27 | import androidx.datastore.preferences.core.stringPreferencesKey
28 | import androidx.datastore.preferences.core.stringSetPreferencesKey
29 | import com.russhwolf.settings.coroutines.FlowSettings
30 | import kotlinx.coroutines.flow.Flow
31 | import kotlinx.coroutines.flow.distinctUntilChanged
32 | import kotlinx.coroutines.flow.first
33 | import kotlinx.coroutines.flow.map
34 |
35 | // TODO: copied from https://github.com/russhwolf/multiplatform-settings/blob/master/multiplatform-settings-datastore/src/androidMain/kotlin/com/russhwolf/settings/datastore/DataStoreSettings.kt
36 | // because of collision between multiplatform-settings-coroutines-native-mt
37 | // and multiplatform-settings-coroutines modules
38 | public class DataStoreSettings(private val datastore: DataStore) : FlowSettings {
39 | public override suspend fun keys(): Set =
40 | datastore.data.first().asMap().keys.map { it.name }.toSet()
41 |
42 | public override suspend fun size(): Int = datastore.data.first().asMap().size
43 | public override suspend fun clear(): Unit = keys().forEach { remove(it) }
44 |
45 | public override suspend fun remove(key: String) {
46 | datastore.edit { it.remove(stringSetPreferencesKey(key)) }
47 | }
48 |
49 | public override suspend fun hasKey(key: String): Boolean =
50 | datastore.data.first().contains(stringSetPreferencesKey(key))
51 |
52 | public override suspend fun putInt(key: String, value: Int) {
53 | datastore.edit { it[intPreferencesKey(key)] = value }
54 | }
55 |
56 | public override fun getIntFlow(key: String, defaultValue: Int): Flow =
57 | getValue { it[intPreferencesKey(key)] ?: defaultValue }
58 |
59 | public override fun getIntOrNullFlow(key: String): Flow =
60 | getValue { it[intPreferencesKey(key)] }
61 |
62 | public override suspend fun putLong(key: String, value: Long) {
63 | datastore.edit { it[longPreferencesKey(key)] = value }
64 | }
65 |
66 | public override fun getLongFlow(key: String, defaultValue: Long): Flow =
67 | getValue { it[longPreferencesKey(key)] ?: defaultValue }
68 |
69 | public override fun getLongOrNullFlow(key: String): Flow =
70 | getValue { it[longPreferencesKey(key)] }
71 |
72 | public override suspend fun putString(key: String, value: String) {
73 | datastore.edit { it[stringPreferencesKey(key)] = value }
74 | }
75 |
76 | public override fun getStringFlow(key: String, defaultValue: String): Flow =
77 | getValue { it[stringPreferencesKey(key)] ?: defaultValue }
78 |
79 | public override fun getStringOrNullFlow(key: String): Flow =
80 | getValue { it[stringPreferencesKey(key)] }
81 |
82 | public override suspend fun putFloat(key: String, value: Float) {
83 | datastore.edit { it[floatPreferencesKey(key)] = value }
84 | }
85 |
86 | public override fun getFloatFlow(key: String, defaultValue: Float): Flow =
87 | getValue { it[floatPreferencesKey(key)] ?: defaultValue }
88 |
89 | public override fun getFloatOrNullFlow(key: String): Flow =
90 | getValue { it[floatPreferencesKey(key)] }
91 |
92 | public override suspend fun putDouble(key: String, value: Double) {
93 | datastore.edit { it[doublePreferencesKey(key)] = value }
94 | }
95 |
96 | public override fun getDoubleFlow(key: String, defaultValue: Double): Flow =
97 | getValue { it[doublePreferencesKey(key)] ?: defaultValue }
98 |
99 | public override fun getDoubleOrNullFlow(key: String): Flow =
100 | getValue { it[doublePreferencesKey(key)] }
101 |
102 | public override suspend fun putBoolean(key: String, value: Boolean) {
103 | datastore.edit { it[booleanPreferencesKey(key)] = value }
104 | }
105 |
106 | public override fun getBooleanFlow(key: String, defaultValue: Boolean): Flow =
107 | getValue { it[booleanPreferencesKey(key)] ?: defaultValue }
108 |
109 | public override fun getBooleanOrNullFlow(key: String): Flow =
110 | getValue { it[booleanPreferencesKey(key)] }
111 |
112 | private inline fun getValue(crossinline getValue: (Preferences) -> T): Flow =
113 | datastore.data.map { getValue(it) }.distinctUntilChanged()
114 | }
115 |
--------------------------------------------------------------------------------
/shared/src/androidMain/kotlin/eu/rajniak/cat/utils/Settings.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import android.content.Context
4 | import androidx.datastore.preferences.preferencesDataStore
5 | import androidx.startup.Initializer
6 | import com.russhwolf.settings.coroutines.FlowSettings
7 |
8 | private var appContext: Context? = null
9 |
10 | private val Context.dataStore by preferencesDataStore(
11 | name = "settings"
12 | )
13 |
14 | actual fun settings(): FlowSettings =
15 | DataStoreSettings(
16 | appContext?.dataStore ?: throw IllegalStateException("Context not initialized")
17 | )
18 |
19 | internal class SettingsInitializer : Initializer {
20 | override fun create(context: Context): Context =
21 | context.applicationContext.also { appContext = it }
22 |
23 | override fun dependencies(): List>> = emptyList()
24 | }
25 |
--------------------------------------------------------------------------------
/shared/src/androidMain/kotlin/eu/rajniak/cat/utils/SharedViewModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import kotlinx.coroutines.CoroutineScope
6 |
7 | @Suppress("EmptyDefaultConstructor")
8 | actual open class SharedViewModel actual constructor() : ViewModel() {
9 | protected actual val sharedScope: CoroutineScope = viewModelScope
10 |
11 | public actual override fun onCleared() {
12 | super.onCleared()
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/CatViewerServiceLocator.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import kotlinx.coroutines.Dispatchers
4 |
5 | object CatViewerServiceLocator {
6 |
7 | val catsStore by lazy {
8 | CatsStoreImpl()
9 | }
10 |
11 | val defaultDispatcher = Dispatchers.Default
12 | }
13 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/CatsApi.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import eu.rajniak.cat.data.Cat
4 | import eu.rajniak.cat.data.Category
5 | import io.ktor.client.HttpClient
6 | import io.ktor.client.call.body
7 | import io.ktor.client.plugins.ContentNegotiation
8 | import io.ktor.client.request.get
9 | import io.ktor.client.request.headers
10 | import io.ktor.client.request.parameter
11 | import io.ktor.client.request.url
12 | import io.ktor.http.Url
13 | import io.ktor.serialization.kotlinx.json.json
14 | import kotlinx.serialization.json.Json
15 |
16 | interface CatsApi {
17 | suspend fun fetchCats(page: Int): List
18 | suspend fun fetchCategories(): List
19 | }
20 |
21 | class CatsApiImpl : CatsApi {
22 |
23 | private val catsUrl =
24 | Url("https://api.thecatapi.com/v1/images/search")
25 |
26 | private val categoriesUrl =
27 | Url("https://api.thecatapi.com/v1/categories")
28 |
29 | private val client = HttpClient() {
30 | install(ContentNegotiation) {
31 | json(
32 | Json {
33 | ignoreUnknownKeys = true
34 | }
35 | )
36 | }
37 | }
38 |
39 | // TODO: find if there is a way of how to tell that there are no more pages
40 | override suspend fun fetchCats(page: Int): List {
41 | return client.get {
42 | url(catsUrl.toString())
43 | headers {
44 | append("x-api-key", BuildKonfig.api_key)
45 | }
46 | parameter("limit", 50)
47 | parameter("page", page)
48 | parameter("order", "ASC")
49 | }.body()
50 | }
51 |
52 | override suspend fun fetchCategories(): List {
53 | return client.get {
54 | url(categoriesUrl.toString())
55 | headers {
56 | append("x-api-key", BuildKonfig.api_key)
57 | }
58 | }.body()
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/CatsStore.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import eu.rajniak.cat.data.Cat
4 | import eu.rajniak.cat.data.Category
5 | import eu.rajniak.cat.data.CategoryModel
6 | import eu.rajniak.cat.data.MimeType
7 | import eu.rajniak.cat.data.MimeTypeModel
8 | import eu.rajniak.cat.data.MimeTypesSource
9 | import eu.rajniak.cat.data.MimeTypesSourceImpl
10 | import eu.rajniak.cat.utils.AtomicInt
11 | import kotlinx.coroutines.flow.Flow
12 | import kotlinx.coroutines.flow.MutableStateFlow
13 | import kotlinx.coroutines.flow.combine
14 |
15 | interface CatsStore {
16 | val cats: Flow>
17 | val categories: Flow>
18 | val mimeTypes: Flow>
19 |
20 | suspend fun start()
21 | suspend fun fetchMoreData()
22 | suspend fun changeCategoryState(categoryId: Int, enabled: Boolean)
23 | suspend fun changeMimeTypeState(mimeTypeId: Int, enabled: Boolean)
24 | }
25 |
26 | class CatsStoreImpl(
27 | private val catsApi: CatsApi = CatsApiImpl(),
28 | private val mimeTypesSource: MimeTypesSource = MimeTypesSourceImpl,
29 | private val settingsStorage: SettingsStorage = SettingsStorageImpl()
30 | ) : CatsStore {
31 |
32 | private val _disabledCategories: Flow> = settingsStorage.disabledCategories
33 |
34 | private val _categories = MutableStateFlow(listOf())
35 | override val categories =
36 | _categories.combine(_disabledCategories) { categories, disabledCategories ->
37 | categories.map { category ->
38 | CategoryModel(
39 | id = category.id,
40 | name = category.name,
41 | enabled = !disabledCategories.contains(category.id)
42 | )
43 | }
44 | }
45 |
46 | private val _disabledMimeTypes: Flow> = settingsStorage.disabledMimeTypes
47 |
48 | // It would be nice if CatsAPI provided available MimeTypes as well,
49 | // so keeping it here in case they do :)
50 | private val _mimeTypes = MutableStateFlow(listOf())
51 | override val mimeTypes =
52 | _mimeTypes.combine(_disabledMimeTypes) { mimeTypes, disabledMimeTypes ->
53 | mimeTypes.map { mimeType ->
54 | MimeTypeModel(
55 | id = mimeType.id,
56 | name = mimeType.name,
57 | enabled = !disabledMimeTypes.contains(mimeType.id)
58 | )
59 | }
60 | }
61 |
62 | override val cats = MutableStateFlow(listOf())
63 |
64 | private var page = AtomicInt(1)
65 |
66 | override suspend fun start() {
67 | _mimeTypes.value = mimeTypesSource.mimeTypes
68 | _categories.value = catsApi.fetchCategories()
69 | cats.value = catsApi.fetchCats(page.get())
70 | }
71 |
72 | override suspend fun fetchMoreData() {
73 | val oldList = cats.value
74 | val newList = catsApi.fetchCats(page.addAndGet(1))
75 | cats.value = listOf(oldList, newList).flatten()
76 | }
77 |
78 | override suspend fun changeCategoryState(categoryId: Int, enabled: Boolean) {
79 | settingsStorage.changeCategoryState(categoryId, enabled)
80 | }
81 |
82 | override suspend fun changeMimeTypeState(mimeTypeId: Int, enabled: Boolean) {
83 | settingsStorage.changeMimeTypeState(mimeTypeId, enabled)
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/CatsViewModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import co.touchlab.kermit.Logger
4 | import eu.rajniak.cat.data.Cat
5 | import eu.rajniak.cat.data.CategoryModel
6 | import eu.rajniak.cat.data.MimeTypeModel
7 | import eu.rajniak.cat.utils.AtomicReference
8 | import eu.rajniak.cat.utils.CommonFlow
9 | import eu.rajniak.cat.utils.SharedViewModel
10 | import eu.rajniak.cat.utils.asCommonFlow
11 | import kotlinx.coroutines.CoroutineDispatcher
12 | import kotlinx.coroutines.Job
13 | import kotlinx.coroutines.flow.combine
14 | import kotlinx.coroutines.launch
15 |
16 | class CatsViewModel(
17 | private val catsStore: CatsStore = CatViewerServiceLocator.catsStore,
18 | private val dispatcher: CoroutineDispatcher = CatViewerServiceLocator.defaultDispatcher
19 | ) : SharedViewModel() {
20 |
21 | val categories: CommonFlow> = catsStore.categories.asCommonFlow()
22 |
23 | val mimeTypes: CommonFlow> = catsStore.mimeTypes.asCommonFlow()
24 |
25 | private val _cats = catsStore.cats
26 | val cats: CommonFlow> =
27 | combine(
28 | _cats,
29 | categories,
30 | mimeTypes,
31 | ) { cats, categories, mimeTypes ->
32 | cats.filter { cat ->
33 | cat.categories.forEach { category ->
34 | if (categories.firstOrNull { it.id == category.id }?.enabled == false) {
35 | return@filter false
36 | }
37 | }
38 | mimeTypes.forEach { mimeType ->
39 | if (cat.url.endsWith(mimeType.name)) {
40 | return@filter mimeType.enabled
41 | }
42 | }
43 | true
44 | }
45 | }.asCommonFlow()
46 |
47 | // TODO: using AtomicReference
48 | // because of issues with freezing state on iOS.
49 | // Try figure out what is wrong (should be one thread access).
50 | private var loadingJob: AtomicReference = AtomicReference(null)
51 |
52 | init {
53 | sharedScope.launch(context = dispatcher) {
54 | try {
55 | catsStore.start()
56 | } catch (exception: Exception) {
57 | Logger.withTag(TAG).e("Failed to start.", exception)
58 | // TODO: do not continue and show whole screen error
59 | }
60 | }
61 | }
62 |
63 | fun onCategoryChecked(categoryId: Int, checked: Boolean) {
64 | sharedScope.launch(context = dispatcher) {
65 | try {
66 | catsStore.changeCategoryState(categoryId, checked)
67 | } catch (exception: Exception) {
68 | Logger.withTag(TAG).e("Failed to change category selection.", exception)
69 | // TODO: show temporary error message (UI should also show original value)
70 | }
71 | }
72 | }
73 |
74 | fun onMimeTypeChecked(mimeTypeId: Int, checked: Boolean) {
75 | sharedScope.launch(context = dispatcher) {
76 | try {
77 | catsStore.changeMimeTypeState(mimeTypeId, checked)
78 | } catch (exception: Exception) {
79 | Logger.withTag(TAG).e("Failed to change mime type selection.", exception)
80 | // TODO: show temporary error message (UI should also show original value)
81 | }
82 | }
83 | }
84 |
85 | // TODO: use multiplatform paging library instead (https://github.com/kuuuurt/multiplatform-paging)
86 | fun onScrolledToTheEnd() {
87 | Logger.withTag("CatsViewModel").i("onScrolledToTheEnd")
88 | if (loadingJob.get()?.isActive == true) {
89 | return
90 | }
91 | val job = sharedScope.launch(context = dispatcher) {
92 | try {
93 | catsStore.fetchMoreData()
94 | } catch (exception: Exception) {
95 | Logger.withTag(TAG).e("Failed to fetch more data.", exception)
96 | // TODO: how to unblock? either try later or let user manually refresh
97 | }
98 | }
99 | loadingJob.set(job)
100 | }
101 |
102 | companion object {
103 |
104 | private const val TAG = "CatsViewModel"
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/SettingsStorage.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import com.russhwolf.settings.coroutines.FlowSettings
4 | import eu.rajniak.cat.utils.settings
5 | import kotlinx.coroutines.GlobalScope
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.map
8 | import kotlinx.coroutines.launch
9 | import kotlinx.serialization.decodeFromString
10 | import kotlinx.serialization.encodeToString
11 | import kotlinx.serialization.json.Json
12 |
13 | interface SettingsStorage {
14 |
15 | val disabledCategories: Flow>
16 | val disabledMimeTypes: Flow>
17 |
18 | suspend fun changeCategoryState(categoryId: Int, enabled: Boolean)
19 | suspend fun changeMimeTypeState(mimeTypeId: Int, enabled: Boolean)
20 | }
21 |
22 | class SettingsStorageImpl(
23 | private val settings: FlowSettings = settings()
24 | ) : SettingsStorage {
25 |
26 | companion object {
27 |
28 | private const val SETTINGS_DISABLED_CATEGORIES = "disabled_categories"
29 | private const val SETTINGS_DISABLED_MIME_TYPES = "disabled_mime_types"
30 | }
31 |
32 | override val disabledCategories: Flow> =
33 | settings.getStringOrNullFlow(SETTINGS_DISABLED_CATEGORIES)
34 | .map {
35 | if (it == null) return@map emptySet()
36 | Json.decodeFromString(it)
37 | }
38 |
39 | override val disabledMimeTypes: Flow> =
40 | settings.getStringOrNullFlow(SETTINGS_DISABLED_MIME_TYPES)
41 | .map {
42 | if (it == null) return@map emptySet()
43 | Json.decodeFromString(it)
44 | }
45 |
46 | init {
47 | // TODO: just for exercise - remove afterwards
48 | // Assignment requirement - filter out hats
49 | GlobalScope.launch {
50 | if (settings.hasKey(SETTINGS_DISABLED_CATEGORIES)) {
51 | // Already set
52 | return@launch
53 | }
54 | val hatsCategoryId = 1
55 | changeCategoryState(hatsCategoryId, false)
56 | }
57 | }
58 |
59 | override suspend fun changeCategoryState(categoryId: Int, enabled: Boolean) {
60 | val disabledCategoriesSerialized = settings.getStringOrNull(SETTINGS_DISABLED_CATEGORIES)
61 | val disabledCategories: MutableSet = if (disabledCategoriesSerialized == null) {
62 | mutableSetOf()
63 | } else {
64 | Json.decodeFromString(disabledCategoriesSerialized)
65 | }
66 |
67 | val result = if (enabled) {
68 | disabledCategories.minus(categoryId)
69 | } else {
70 | disabledCategories.plus(categoryId)
71 | }
72 | val resultSerialized = Json.encodeToString(result)
73 |
74 | settings.putString(SETTINGS_DISABLED_CATEGORIES, resultSerialized)
75 | }
76 |
77 | override suspend fun changeMimeTypeState(mimeTypeId: Int, enabled: Boolean) {
78 | val disabledMimeTypesSerialized = settings.getStringOrNull(SETTINGS_DISABLED_MIME_TYPES)
79 | val disabledMimeTypes: MutableSet = if (disabledMimeTypesSerialized == null) {
80 | mutableSetOf()
81 | } else {
82 | Json.decodeFromString(disabledMimeTypesSerialized)
83 | }
84 |
85 | val result = if (enabled) {
86 | disabledMimeTypes.minus(mimeTypeId)
87 | } else {
88 | disabledMimeTypes.plus(mimeTypeId)
89 | }
90 | val resultSerialized = Json.encodeToString(result)
91 |
92 | settings.putString(SETTINGS_DISABLED_MIME_TYPES, resultSerialized)
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/Cat.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | import com.benasher44.uuid.uuid4
4 | import kotlinx.serialization.Serializable
5 |
6 | @Serializable
7 | data class Cat(
8 | val id: String = uuid4().toString(),
9 | val url: String,
10 | val categories: List = listOf()
11 | )
12 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/Category.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | import kotlinx.serialization.Serializable
4 |
5 | @Serializable
6 | data class Category(
7 | val id: Int,
8 | val name: String
9 | )
10 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/CategoryModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | data class CategoryModel(
4 | val id: Int,
5 | val name: String,
6 | // TODO: var so that it can be used in iOS as a State
7 | // see if we can avoid changing model directly
8 | var enabled: Boolean
9 | )
10 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/FakeData.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | import kotlin.jvm.JvmStatic
4 |
5 | object FakeData {
6 |
7 | private const val IMAGE_URL_JPG = "https://cdn2.thecatapi.com/images/YEw66vQ9A.jpg"
8 | private const val IMAGE_URL_GIF = "https://cdn2.thecatapi.com/images/497.gif"
9 |
10 | @JvmStatic
11 | val CATEGORY_HATS = Category(
12 | id = 1,
13 | name = "hats"
14 | )
15 |
16 | @JvmStatic
17 | val CATEGORY_SPACE = Category(
18 | id = 2,
19 | name = "space"
20 | )
21 |
22 | private val imageUrls = listOf(
23 | IMAGE_URL_JPG,
24 | IMAGE_URL_GIF
25 | )
26 |
27 | val cats = generateCats(50)
28 |
29 | private fun generateCats(size: Int): List {
30 | val result = mutableListOf()
31 | repeat(size) {
32 | result.add(
33 | Cat(
34 | url = imageUrls.random(),
35 | categories = listOf(CATEGORY_HATS, CATEGORY_SPACE, null, null)
36 | .shuffled()
37 | .take(2)
38 | .filterNotNull()
39 | )
40 | )
41 | }
42 | return result
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/MimeType.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | data class MimeType(
4 | val id: Int,
5 | val name: String
6 | )
7 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/MimeTypeModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | data class MimeTypeModel(
4 | val id: Int,
5 | val name: String,
6 | // TODO: var so that it can be used in iOS as a State
7 | // see if we can avoid changing model directly
8 | var enabled: Boolean
9 | )
10 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/data/MimeTypesSource.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.data
2 |
3 | import kotlin.jvm.JvmStatic
4 |
5 | interface MimeTypesSource {
6 |
7 | val mimeTypes: List
8 | }
9 |
10 | object MimeTypesSourceImpl : MimeTypesSource {
11 |
12 | @JvmStatic
13 | private val MIME_TYPE_GIF = MimeType(
14 | id = 1,
15 | name = "gif"
16 | )
17 |
18 | @JvmStatic
19 | private val MIME_TYPE_JPG = MimeType(
20 | id = 2,
21 | name = "jpg"
22 | )
23 |
24 | @JvmStatic
25 | private val MIME_TYPE_PNG = MimeType(
26 | id = 3,
27 | name = "png"
28 | )
29 |
30 | override val mimeTypes = listOf(
31 | MIME_TYPE_GIF,
32 | MIME_TYPE_JPG,
33 | MIME_TYPE_PNG
34 | )
35 | }
36 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/utils/AtomicInt.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | expect class AtomicInt(initialValue: Int) {
4 | fun get(): Int
5 | fun addAndGet(delta: Int): Int
6 | }
7 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/utils/AtomicReference.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | expect class AtomicReference constructor(initialValue: V) {
4 | fun set(value: V)
5 | fun get(): V
6 | }
7 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/utils/CommonFlow.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import kotlinx.coroutines.CoroutineScope
4 | import kotlinx.coroutines.Dispatchers
5 | import kotlinx.coroutines.Job
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.launchIn
8 | import kotlinx.coroutines.flow.onEach
9 |
10 | fun Flow.asCommonFlow(): CommonFlow = CommonFlow(this)
11 |
12 | class CommonFlow(private val origin: Flow) : Flow by origin {
13 | fun watch(block: (T) -> Unit): Closeable {
14 | val job = Job()
15 | onEach { block(it) }.launchIn(CoroutineScope(job + Dispatchers.Main))
16 |
17 | return object : Closeable {
18 | override fun close() {
19 | job.cancel()
20 | }
21 | }
22 | }
23 | }
24 |
25 | interface Closeable {
26 | fun close()
27 | }
28 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/utils/Settings.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import com.russhwolf.settings.coroutines.FlowSettings
4 |
5 | expect fun settings(): FlowSettings
6 |
--------------------------------------------------------------------------------
/shared/src/commonMain/kotlin/eu/rajniak/cat/utils/SharedViewModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import kotlinx.coroutines.CoroutineScope
4 |
5 | @Suppress("EmptyDefaultConstructor")
6 | expect open class SharedViewModel() {
7 | protected val sharedScope: CoroutineScope
8 |
9 | open fun onCleared()
10 | }
11 |
--------------------------------------------------------------------------------
/shared/src/commonTest/kotlin/eu/rajniak/cat/CatsTest.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat
2 |
3 | import co.touchlab.kermit.ExperimentalKermitApi
4 | import co.touchlab.kermit.Logger
5 | import co.touchlab.kermit.Severity
6 | import co.touchlab.kermit.TestLogWriter
7 | import eu.rajniak.cat.data.Cat
8 | import eu.rajniak.cat.data.Category
9 | import eu.rajniak.cat.data.MimeType
10 | import eu.rajniak.cat.data.MimeTypesSource
11 | import kotlinx.coroutines.ExperimentalCoroutinesApi
12 | import kotlinx.coroutines.flow.MutableStateFlow
13 | import kotlinx.coroutines.flow.first
14 | import kotlinx.coroutines.test.StandardTestDispatcher
15 | import kotlinx.coroutines.test.TestDispatcher
16 | import kotlinx.coroutines.test.runTest
17 | import kotlin.test.BeforeTest
18 | import kotlin.test.Test
19 | import kotlin.test.assertEquals
20 | import kotlin.test.assertFalse
21 | import kotlin.test.assertTrue
22 |
23 | // TODO: switch to AssertJ and JUnit for testing
24 | // this doesn't provide useful info
25 | @ExperimentalKermitApi
26 | @ExperimentalCoroutinesApi
27 | class CatsTest {
28 |
29 | companion object {
30 | private val CATEGORY_HAT = Category(
31 | id = 1,
32 | name = "Hat"
33 | )
34 |
35 | private val MIME_TYPE_GIF = MimeType(
36 | id = 1,
37 | name = "gif"
38 | )
39 | }
40 |
41 | private lateinit var dispatcher: TestDispatcher
42 | private lateinit var testLogWriter: TestLogWriter
43 | private lateinit var catsApi: FakeCatsApi
44 | private lateinit var mimeTypesSource: FakeMimeTypesSource
45 | private lateinit var settingsStorage: SettingsStorage
46 | private lateinit var viewModel: CatsViewModel
47 |
48 | @BeforeTest
49 | fun setUp() {
50 | testLogWriter = TestLogWriter(loggable = Severity.Verbose)
51 | // Make sure in tests we do use production logger
52 | // (e.g. on Android LogcatLogger is using system println)
53 | Logger.setLogWriters(testLogWriter)
54 |
55 | catsApi = FakeCatsApi()
56 | catsApi.categories += CATEGORY_HAT
57 | catsApi.cats[1] = listOf(
58 | Cat(
59 | url = "Dummy.gif",
60 | categories = listOf(CATEGORY_HAT)
61 | ),
62 | Cat(
63 | url = "Dummy.png"
64 | )
65 | )
66 | catsApi.cats[2] = listOf(
67 | Cat(
68 | url = "Dummy.jpg"
69 | )
70 | )
71 |
72 | mimeTypesSource = FakeMimeTypesSource()
73 | mimeTypesSource.mimeTypes += MIME_TYPE_GIF
74 |
75 | settingsStorage = FakeSettingsStorage()
76 |
77 | dispatcher = StandardTestDispatcher()
78 |
79 | viewModel = CatsViewModel(
80 | catsStore = CatsStoreImpl(
81 | catsApi = catsApi,
82 | mimeTypesSource = mimeTypesSource,
83 | settingsStorage = settingsStorage
84 | ),
85 | dispatcher = dispatcher
86 | )
87 | }
88 |
89 | @Test
90 | fun testCategorySelectionChange() = runTest(dispatcher) {
91 | assertTrue { viewModel.categories.first().first { it.id == CATEGORY_HAT.id }.enabled }
92 |
93 | viewModel.onCategoryChecked(CATEGORY_HAT.id, false)
94 |
95 | assertFalse { viewModel.categories.first().first { it.id == CATEGORY_HAT.id }.enabled }
96 | }
97 |
98 | @Test
99 | fun testMimeTypeSelectionChange() = runTest(dispatcher) {
100 | assertTrue { viewModel.mimeTypes.first().first { it.id == MIME_TYPE_GIF.id }.enabled }
101 |
102 | viewModel.onMimeTypeChecked(MIME_TYPE_GIF.id, false)
103 |
104 | assertFalse { viewModel.mimeTypes.first().first { it.id == MIME_TYPE_GIF.id }.enabled }
105 | }
106 |
107 | @Test
108 | fun testCategoryCatFilter() = runTest(dispatcher) {
109 | assertEquals(2, viewModel.cats.first().size)
110 |
111 | viewModel.onCategoryChecked(CATEGORY_HAT.id, false)
112 |
113 | assertEquals(1, viewModel.cats.first().size)
114 | }
115 |
116 | @Test
117 | fun testMimeTypeCatFilter() = runTest(dispatcher) {
118 | assertEquals(2, viewModel.cats.first().size)
119 |
120 | viewModel.onMimeTypeChecked(MIME_TYPE_GIF.id, false)
121 |
122 | assertEquals(1, viewModel.cats.first().size)
123 | }
124 |
125 | @Test
126 | fun testPagination() = runTest(dispatcher) {
127 | assertEquals(2, viewModel.cats.first().size)
128 |
129 | viewModel.onScrolledToTheEnd()
130 |
131 | assertEquals(3, viewModel.cats.first().size)
132 | }
133 |
134 | @Test
135 | fun testPaginationLog() = runTest(dispatcher) {
136 | testLogWriter.assertCount(0)
137 |
138 | viewModel.onScrolledToTheEnd()
139 |
140 | testLogWriter.assertCount(1)
141 | testLogWriter.assertLast { message == "onScrolledToTheEnd" }
142 | }
143 | }
144 |
145 | class FakeCatsApi : CatsApi {
146 |
147 | // key: page, value: Cat
148 | val cats = mutableMapOf>()
149 | val categories = mutableListOf()
150 |
151 | override suspend fun fetchCats(page: Int) = cats[page]!!
152 |
153 | override suspend fun fetchCategories() = categories
154 | }
155 |
156 | class FakeMimeTypesSource : MimeTypesSource {
157 |
158 | override val mimeTypes = mutableListOf()
159 | }
160 |
161 | // TODO: if we fake settings instead, we can use real storage with this logic in it
162 | // not needing to rewrite it here
163 | class FakeSettingsStorage : SettingsStorage {
164 |
165 | override val disabledCategories = MutableStateFlow(setOf())
166 | override val disabledMimeTypes = MutableStateFlow(setOf())
167 |
168 | override suspend fun changeCategoryState(categoryId: Int, enabled: Boolean) {
169 | val oldValue = disabledCategories.value
170 | disabledCategories.value = if (enabled) {
171 | oldValue.minus(categoryId)
172 | } else {
173 | oldValue.plus(categoryId)
174 | }
175 | }
176 |
177 | override suspend fun changeMimeTypeState(mimeTypeId: Int, enabled: Boolean) {
178 | val oldValue = disabledMimeTypes.value
179 | disabledMimeTypes.value = if (enabled) {
180 | oldValue.minus(mimeTypeId)
181 | } else {
182 | oldValue.plus(mimeTypeId)
183 | }
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/shared/src/iosMain/kotlin/eu/rajniak/cat/utils/AtomicInt.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import kotlin.native.concurrent.AtomicInt
4 |
5 | actual class AtomicInt actual constructor(initialValue: Int) {
6 | private val atom = AtomicInt(initialValue)
7 |
8 | actual fun get(): Int = atom.value
9 | actual fun addAndGet(delta: Int): Int = atom.addAndGet(delta)
10 | }
11 |
--------------------------------------------------------------------------------
/shared/src/iosMain/kotlin/eu/rajniak/cat/utils/AtomicReference.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import kotlin.native.concurrent.AtomicReference
4 |
5 | actual class AtomicReference actual constructor(initialValue: V) {
6 | private val atom = AtomicReference(initialValue)
7 |
8 | actual fun set(value: V) {
9 | atom.value = value
10 | }
11 | actual fun get(): V = atom.value
12 | }
13 |
--------------------------------------------------------------------------------
/shared/src/iosMain/kotlin/eu/rajniak/cat/utils/Settings.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import com.russhwolf.settings.AppleSettings
4 | import com.russhwolf.settings.coroutines.FlowSettings
5 | import com.russhwolf.settings.coroutines.toFlowSettings
6 | import platform.Foundation.NSUserDefaults
7 |
8 | actual fun settings(): FlowSettings =
9 | AppleSettings(NSUserDefaults.standardUserDefaults, true).toFlowSettings()
10 |
--------------------------------------------------------------------------------
/shared/src/iosMain/kotlin/eu/rajniak/cat/utils/SharedViewModel.kt:
--------------------------------------------------------------------------------
1 | package eu.rajniak.cat.utils
2 |
3 | import kotlinx.coroutines.CoroutineDispatcher
4 | import kotlinx.coroutines.CoroutineScope
5 | import kotlinx.coroutines.cancel
6 | import platform.darwin.dispatch_async
7 | import platform.darwin.dispatch_get_main_queue
8 | import kotlin.native.internal.GC
9 |
10 | @Suppress("EmptyDefaultConstructor")
11 | actual open class SharedViewModel actual constructor() {
12 | protected actual val sharedScope: CoroutineScope = createViewModelScope()
13 |
14 | actual open fun onCleared() {
15 | sharedScope.cancel()
16 |
17 | dispatch_async(dispatch_get_main_queue()) { GC.collect() }
18 | }
19 | }
20 |
21 | @ThreadLocal
22 | private var createViewModelScope: () -> CoroutineScope = {
23 | CoroutineScope(createUIDispatcher())
24 | }
25 |
26 | private fun createUIDispatcher(): CoroutineDispatcher = UIDispatcher()
27 |
--------------------------------------------------------------------------------
/shared/src/iosMain/kotlin/eu/rajniak/cat/utils/UIDispatcher.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
3 | * https://github.com/icerockdev/moko-mvvm
4 | *
5 | * TODO: use MOKO library directly if viable
6 | */
7 | package eu.rajniak.cat.utils
8 |
9 | import kotlinx.coroutines.CancellableContinuation
10 | import kotlinx.coroutines.CoroutineDispatcher
11 | import kotlinx.coroutines.Delay
12 | import kotlinx.coroutines.DisposableHandle
13 | import kotlinx.coroutines.InternalCoroutinesApi
14 | import kotlinx.coroutines.Runnable
15 | import platform.darwin.DISPATCH_TIME_NOW
16 | import platform.darwin.NSEC_PER_MSEC
17 | import platform.darwin.dispatch_after
18 | import platform.darwin.dispatch_async
19 | import platform.darwin.dispatch_get_main_queue
20 | import platform.darwin.dispatch_time
21 | import kotlin.coroutines.CoroutineContext
22 |
23 | @OptIn(ExperimentalUnsignedTypes::class, InternalCoroutinesApi::class)
24 | internal class UIDispatcher : CoroutineDispatcher(), Delay {
25 | private val mQueue = dispatch_get_main_queue()
26 |
27 | override fun dispatch(context: CoroutineContext, block: Runnable) {
28 | dispatch_async(mQueue) {
29 | block.run()
30 | }
31 | }
32 |
33 | override fun scheduleResumeAfterDelay(
34 | timeMillis: Long,
35 | continuation: CancellableContinuation
36 | ) {
37 | dispatch_after(
38 | `when` = dispatch_time(
39 | DISPATCH_TIME_NOW,
40 | timeMillis * NSEC_PER_MSEC.toLong()
41 | ),
42 | queue = mQueue
43 | ) {
44 | val result = continuation.tryResume(Unit)
45 | if (result != null) {
46 | continuation.completeResume(result)
47 | }
48 | }
49 | }
50 |
51 | override fun invokeOnTimeout(
52 | timeMillis: Long,
53 | block: Runnable,
54 | context: CoroutineContext
55 | ): DisposableHandle {
56 | var disposed = false
57 | dispatch_after(
58 | `when` = dispatch_time(
59 | DISPATCH_TIME_NOW,
60 | timeMillis * NSEC_PER_MSEC.toLong()
61 | ),
62 | queue = mQueue
63 | ) {
64 | if (disposed) return@dispatch_after
65 |
66 | block.run()
67 | }
68 | return object : DisposableHandle {
69 | override fun dispose() {
70 | disposed = true
71 | }
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------