├── .gitignore ├── .idea ├── codeStyles │ └── Project.xml ├── encodings.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── sysdata │ │ │ └── kt │ │ │ └── ktandroidarchitecture │ │ │ ├── MainApplication.kt │ │ │ ├── di │ │ │ └── AppModule.kt │ │ │ ├── repository │ │ │ ├── AuthRepositoryImpl.kt │ │ │ ├── GitHubRepo.kt │ │ │ └── model │ │ │ │ ├── UIUserLogged.kt │ │ │ │ └── UserLogged.kt │ │ │ ├── ui │ │ │ ├── GitHubActivity.kt │ │ │ └── LoginActivity.kt │ │ │ ├── usecase │ │ │ ├── GitHubUseCase.kt │ │ │ ├── LoginUseCase.kt │ │ │ └── Params.kt │ │ │ └── viewmodel │ │ │ ├── GitHubViewModel.kt │ │ │ └── LoginViewModel.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_git_hub.xml │ │ └── activity_login.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── sysdata │ └── kt │ └── ktandroidarchitecture │ ├── AuthRepositoryTest.kt │ ├── CheckModulesTest.kt │ ├── GitHubRepositoryTest.kt │ ├── LiveDataTestUtil.kt │ ├── LoginUseCaseTest.kt │ └── LoginViewModelTest.kt ├── build.gradle ├── docs ├── Action.md ├── ActionFlowDiagram-thumbnail.png ├── ActionFlowDiagram.png ├── DI-Dagger.md ├── InstrumentedTests.md ├── Repository.md ├── UI.md ├── UI_to_VM.png ├── UiModel.md ├── UnitTests.md ├── UseCase.md ├── ViewModel.md ├── actionQueue.png ├── actionSingleUseCase.png ├── action_execute.png ├── action_queue_execute.png ├── create_usecase.gif ├── queue_action.gif ├── repository.png ├── settings.zip ├── single_action.gif ├── test │ ├── test_apk_location.png │ ├── test_apk_request_firebase.png │ ├── test_device_results_firebase.png │ ├── test_result.png │ ├── test_run_instrumented_firebase.png │ ├── test_run_test.png │ ├── test_select_devices_firebase.png │ └── test_single_device_result_firebase.png ├── uimodel.png └── usecase.png ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── ktandroidarchitecturecore ├── .gitignore ├── build.gradle ├── proguard-rules.pro ├── publishBintray.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── it │ │ └── sysdata │ │ └── ktandroidarchitecturecore │ │ ├── BaseConfig.kt │ │ ├── BaseRepository.kt │ │ ├── exception │ │ └── Failure.kt │ │ ├── functional │ │ └── Either.kt │ │ ├── interactor │ │ ├── Action.kt │ │ ├── ActionParams.kt │ │ ├── ActionQueue.kt │ │ ├── SingleAction.kt │ │ └── UseCase.kt │ │ └── platform │ │ ├── BaseViewModel.kt │ │ ├── KParcelable.kt │ │ ├── SafeExecute.kt │ │ ├── SafeExecuteInterface.kt │ │ └── SingleLiveEvent.kt │ └── res │ └── values │ └── strings.xml ├── networkmodule ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── example │ │ └── networkmodule │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── networkmodule │ │ │ ├── api │ │ │ ├── api │ │ │ │ ├── GitHubService.kt │ │ │ │ └── GitHubServiceAPI.kt │ │ │ └── model │ │ │ │ └── Repo.kt │ │ │ └── di │ │ │ └── NetworkModule.kt │ └── res │ │ └── values │ │ └── strings.xml │ └── test │ └── java │ └── com │ └── example │ └── networkmodule │ └── ExampleUnitTest.kt └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # IntelliJ 36 | *.iml 37 | .idea/ 38 | 39 | # Keystore files 40 | # Uncomment the following line if you do not want to check your keystore files in. 41 | #*.jks 42 | 43 | # External native build folder generated in Android Studio 2.2 and later 44 | .externalNativeBuild 45 | 46 | # Google Services (e.g. APIs or Firebase) 47 | google-services.json 48 | 49 | # Freeline 50 | freeline.py 51 | freeline/ 52 | freeline_project_description.json 53 | 54 | # fastlane 55 | fastlane/report.xml 56 | fastlane/Preview.html 57 | fastlane/screenshots 58 | fastlane/test_output 59 | fastlane/readme.md 60 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 41 | 42 | 43 | 44 | 45 | 46 | 48 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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 | # KTAndroidArchitecture 2 | A Kotlin android architecture with Google Architecture Components 3 | ## 1. A Brief Introduciton 4 | The app is a sample project that shows how to implement the KTAndroidArchitecture into your Android app. 5 | 6 | ### 1.1 What is KTAndroidArchitecture? 7 | It is a layer-based architecture that allows a real decoupling of the UI components from the business logic. 8 | 9 | ![alt text](https://cdn-images-1.medium.com/max/800/1*I9WPcnpGNuI4CjxxrkP0-g.png "Simple Architecture Diagram") 10 | 11 | The main components are: 12 | 13 | * [UIModel](docs/UiModel.md) 14 | * [UseCase](docs/UseCase.md) 15 | * [Repository](docs/Repository.md) 16 | * [Action](docs/Action.md) 17 | 18 | Here you can find a list of guides depending on your implementations : 19 | * [DI - Use with Dagger](docs/DI-Dagger.md) 20 | * [Instrumented Tests with Espresso](docs/InstrumentedTests.md) 21 | * [Unit Tests with Koin](docs/UnitTests.md) 22 | 23 | ## 2. How to use it? 24 | 25 | ### 2.1 Import dependency 26 | 27 | #### 2.1.1 in **Project level `build.gradle`** add this repository 28 | ```gradle 29 | maven { url 'https://dl.bintray.com/sysdata/maven' } 30 | ``` 31 | #### 2.1.2 in your **App level `build.gradle`** add this dependecy 32 | ```gradle 33 | implementation 'it.sysdata.mobile:ktandroidarchitecturecore:1.0.3' 34 | ``` 35 | 36 | #### 2.1.3 import the settings for use live template and file template 37 | 38 | * [Settings.zip](docs/settings.zip) 39 | 40 | 41 | ### 2.2 Create a Repository 42 | A repository just needs to extend **BaseRepository** in this way 43 | ```kotlin 44 | class AuthRepository:BaseRepository() 45 | ``` 46 | 47 | ### 2.3 Create a UseCase 48 | A usecase has to extend **UseCase** and implement a the "run" method: 49 | ```kotlin 50 | class LoginUseCase: UseCase() { 51 | override suspend fun run(params: LoginActionParams): Either { 52 | do something 53 | return result 54 | } 55 | } 56 | ``` 57 | or you can just create a new usecase by going to File Template New->Kotlin Use Case 58 | 59 | ![alt text](docs/create_usecase.gif) 60 | 61 | 62 | The "run" function defined inside the UseCase can return a **Failure object** or a **Model object**. 63 | 64 | The input params are defined in a Param object which is a data class defined like this 65 | ```kotlin 66 | data class LoginActionParams(val email: String, val password: String) : ActionParams() 67 | ``` 68 | 69 | ### 2.4 Create a ViewModel for your Activity/Fragment 70 | 71 | A ViewModel needs to extend the abstract class BaseViewModel 72 | ```kotlin 73 | class LoginViewModel: BaseViewModel() 74 | ``` 75 | 76 | #### 2.4.1 Define an Action inside the ViewModel 77 | 78 | An **Action** can be created by using a Builder like this 79 | ```kotlin 80 | val actionLogin = Action.Builder() 81 | .useCase(LoginUseCase::class.java) 82 | .buildWithUiModel { UiModel(it) } 83 | ``` 84 | or you can just use the live template **ac** to create a usecase straight from the class! 85 | 86 | ![alt text](docs/single_action.gif) 87 | 88 | The flow is composed by the following steps: 89 | 90 | 1. The execution of an Action performed by the method execute(...) of Action class. 91 | 2. The first logical step is the post of an object inside an internal livedata called LoadingLiveData indicating that loading has started. The UI can observe this LiveData using the method observeLoadingStatus(...). 92 | 3. The next step is the execution of a usecase which uses repositories to retrieve some data. 93 | 4. The result of repositories' call is returned to the usecase. 94 | 5. The post of an object inside an internal livedata called LoadingLivedata indicating that loading has finished. The UI can observe this LiveData using the method observeLoadingStatus(...) 95 | 6. the post of the usecase result in two internal livedatas based on the success or the failure; the UI can observe these two LiveDatas by using observe(...) and observeFailure(...) 96 | 97 | ![alt text](docs/ActionFlowDiagram.png) 98 | 99 | ### 2.5 Call the Action from the Activity/Fragment 100 | 101 | ![alt text](docs/UI_to_VM.png) 102 | 103 | An action has several methods like: 104 | - ``` action.observe(...) ```, this method observes the success of the operation defined inside the usecase; 105 | - ``` action.observeFailure(...) ```, this method observes the failure of the operation; 106 | - ``` action.observeLoadingStatus(...) ```, this method observes the loading state of the operation; 107 | - ``` action.execute(...) ```, this method calls the "run" function inside the usecase and executes the operation; 108 | - ``` action.safeExecute(...) ```, this method calls the "run" function inside the usecase and executes the operation into in a SafeExecuteInterface; 109 | 110 | ### 2.6 Custom safe executor 111 | The `safeExecute()` method call is meant to be used if you plan a different behaviour based on the error of your response. 112 | If you use the simple `execute()` call, whenever there's an error, the method will throw an exception and you will have to 113 | handle it by try-catching it and defining a behaviour for that UseCase. 114 | If you use the `safeExecute()` method call, whenever there's an error, it will fallback to an `InternalError` failure in case of 115 | an exception, saving you from an application crash. 116 | Moreover, if you'd like to customize the behaviour in a general way, you can define a class that extends from the `SafeExecuteInterface` 117 | and inside the overridden `safeExecute()` call you can define the custom behaviour you want for your application. 118 | Finally, you'll have to assign the custom `SafeExecutor` as the `BaseConfig.safeExecutor` variable. 119 | 120 | ```kotlin 121 | BaseConfig.safeExecutor = MySafeExecutor() 122 | ``` 123 | 124 | It is suggested that you assign this variable as soon as possible (i.e. in the `Application`'s class `onCreate()` method). 125 | 126 | 127 | To call an action you have to write this: 128 | ```kotlin 129 | viewModel.action.observe(this, ::onActionSuccess) 130 | viewModel.action.observeFailure(this, ::onActionFailed) 131 | viewModel.action.execute(Params) 132 | ``` 133 | 134 | ## 3 KTAndroidArchitecture main components 135 | 136 | ### 3.1 UI 137 | 138 | The UI layer of the architecture includes Activities, Fragments and Views. 139 | 140 | ### 3.2 UIModel 141 | 142 | A **UIModel** is an object that contains all UI-related datas of a view, fragment or activity. 143 | 144 | [Read More](docs/UiModel.md) 145 | 146 | ### 3.3 ViewModels with Livedata 147 | 148 | Each activity or fragment could have a **ViewModel** which is an object designed to store and manage UI-related data in a lifecycle aware way by defining some **Actions** to call one or more **UseCases** 149 | 150 | ### 3.4 UseCase 151 | A **UseCase** is a wrapper for a small business logic operation. A **UseCase** can use one or more **Repository** to retrieve or to set data, then it returns the response event. 152 | 153 | [Read More](docs/UseCase.md) 154 | 155 | ### 3.5 Repository 156 | A **Repository** handles the process of saving or retrieving data from a datasource, it is managed by one or more **UseCase**. 157 | 158 | [Read More](docs/Repository.md) 159 | 160 | ### 3.6 Action 161 | An **Action** handles the process of calling a **UseCase** and map the response. Usually, an action uses only one **UseCase**, but it is possible to define an **ActionQueue** in order to call multiple **UseCases** sequentially. 162 | Into an **ActionQueue** each **UseCase**, except the first, takes the result of the previous as parameters and gives the output to the next one. 163 | 164 | **Action** 165 | 166 | ![alt text](docs/actionSingleUseCase.png "Action") 167 | 168 | ```kotlin 169 | val actionLogin = Action.Builder() 170 | .useCase(LoginUseCase::class.java) 171 | .buildWithUiModel { UiModel(it) } 172 | ``` 173 | 174 | **ActionQueue** 175 | 176 | ![alt text](docs/actionQueue.png "ActionQueue") 177 | 178 | ```kotlin 179 | val actionQueue = ActionQueue.Builder() 180 | .setFirstUseCase(FirstUseCase::class.java) 181 | .addUseCase(...) 182 | .setLastUseCase(...) 183 | ``` 184 | or just **acq** command live template 185 | 186 | ![alt text](docs/queue_action.gif) 187 | 188 | Optionally, you can add a CoroutineScope to the action. 189 | 190 | ```kotlin 191 | actionLogin.execute(LoginActionParams(username, password), viewModelScope) 192 | ``` 193 | 194 | For more informations about the CoroutineScope, 195 | please refer to this articles : 196 | - https://medium.com/androiddevelopers/easy-coroutines-in-android-viewmodelscope-25bffb605471 197 | - https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/ 198 | 199 | ### 3.7 Testing 200 | 201 | #### 3.7.1 InstrumentedTests 202 | It is possible to perform instrumented tests on the architecture. 203 | To learn more about instrumented tests, please, refer to the following section: [Instrumented Tests](docs/InstrumentedTests.md) 204 | 205 | #### 3.7.2 Unit test 206 | It is possible to perform unit tests on the architecture. 207 | To learn more about unit tests, please, refer to the following section: [Unit tests](docs/UnitTests.md) 208 | 209 | ## CHANGELOG ## 210 | 211 | **1.0.3** 212 | - added safeExecute. 213 | 214 | **1.0.2** 215 | - Added Scope to actions. 216 | 217 | **1.0.1** 218 | - fixed abnormal behavior on ActionQueue. 219 | - Added the possibility to add the action instance instead of the class. This is useful for dependency injection (i.e. Dagger). 220 | - Added ActionSingle. 221 | - fixed the behavior of the error post in the observeFailure function. 222 | - Updated Gradle plugin version. 223 | 224 | # License 225 | 226 | Copyright (C) 2020 Sysdata S.p.A. 227 | 228 | Licensed under the Apache License, Version 2.0 (the "License"); 229 | you may not use this file except in compliance with the License. 230 | You may obtain a copy of the License at 231 | 232 | http://www.apache.org/licenses/LICENSE-2.0 233 | 234 | Unless required by applicable law or agreed to in writing, software 235 | distributed under the License is distributed on an "AS IS" BASIS, 236 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 237 | See the License for the specific language governing permissions and 238 | limitations under the License. 239 | 240 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | apply plugin: 'kotlin-kapt' 5 | 6 | android { 7 | compileSdkVersion 28 8 | defaultConfig { 9 | applicationId "com.sysdata.kt.ktandroidarchitecture" 10 | minSdkVersion 19 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | 23 | packagingOptions { 24 | exclude 'META-INF/main.kotlin_module' 25 | } 26 | } 27 | 28 | dependencies { 29 | def ktx_version = "2.0.0" 30 | implementation fileTree(dir: 'libs', include: ['*.jar']) 31 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 32 | implementation 'androidx.appcompat:appcompat:1.1.0' 33 | implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-experimental-adapter:1.0.0' 34 | implementation "com.google.android.material:material:1.2.0-alpha03" 35 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 36 | kapt "androidx.databinding:databinding-compiler:3.5.3" 37 | implementation "androidx.lifecycle:lifecycle-extensions:2.1.0" 38 | implementation "androidx.lifecycle:lifecycle-viewmodel:2.1.0" 39 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$ktx_version" 40 | implementation "androidx.fragment:fragment-ktx:1.2.0-rc04" 41 | implementation project(':networkmodule') 42 | 43 | implementation project(':ktandroidarchitecturecore') 44 | testImplementation 'junit:junit:4.13' 45 | androidTestImplementation 'androidx.test:runner:1.2.0' 46 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 47 | testImplementation 'org.mockito:mockito-core:3.1.0' 48 | testImplementation 'android.arch.core:core-testing:1.1.1' 49 | testImplementation 'com.jraska.livedata:testing-ktx:1.1.0' 50 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2" 51 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2" 52 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.0" 53 | // Koin for Unit tests 54 | testImplementation "org.koin:koin-test:$koin_version" 55 | 56 | } 57 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/MainApplication.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture 2 | 3 | import android.app.Application 4 | import com.example.networkmodule.di.networkModule 5 | import com.sysdata.kt.ktandroidarchitecture.di.appModule 6 | import org.koin.android.ext.koin.androidContext 7 | import org.koin.android.ext.koin.androidLogger 8 | import org.koin.core.context.startKoin 9 | import org.koin.core.logger.Level 10 | 11 | 12 | class MainApplication : Application() { 13 | 14 | 15 | override fun onCreate() { 16 | super.onCreate() 17 | 18 | startKoin { 19 | androidLogger(Level.DEBUG) 20 | androidContext(this@MainApplication) 21 | modules(listOf(appModule, networkModule)) 22 | } 23 | } 24 | 25 | 26 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/di/AppModule.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.di 2 | 3 | import com.sysdata.kt.ktandroidarchitecture.repository.AuthRepository 4 | import com.sysdata.kt.ktandroidarchitecture.repository.AuthRepositoryImpl 5 | import com.sysdata.kt.ktandroidarchitecture.repository.GitHubRepo 6 | import com.sysdata.kt.ktandroidarchitecture.repository.GitHubRepoImpl 7 | import com.sysdata.kt.ktandroidarchitecture.usecase.GitHubUseCase 8 | import com.sysdata.kt.ktandroidarchitecture.usecase.LoginUseCase 9 | import com.sysdata.kt.ktandroidarchitecture.viewmodel.GitHubViewModel 10 | import com.sysdata.kt.ktandroidarchitecture.viewmodel.LoginViewModel 11 | import org.koin.androidx.viewmodel.dsl.viewModel 12 | import org.koin.dsl.module 13 | 14 | val appModule = module{ 15 | // single instance of AuthRepository 16 | single{AuthRepositoryImpl()} 17 | single{GitHubRepoImpl(get())} 18 | 19 | // simple UseCase factory 20 | factory { LoginUseCase(get()) } 21 | factory { GitHubUseCase(get()) } 22 | 23 | // LoginViewModel ViewModel 24 | viewModel { LoginViewModel(get())} 25 | viewModel { GitHubViewModel(get()) } 26 | 27 | 28 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/repository/AuthRepositoryImpl.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.repository 2 | 3 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UserLogged 4 | import it.sysdata.ktandroidarchitecturecore.BaseRepository 5 | 6 | 7 | interface AuthRepository { 8 | fun login(email: String, password: String): UserLogged 9 | 10 | } 11 | 12 | class AuthRepositoryImpl : BaseRepository(),AuthRepository { 13 | 14 | 15 | 16 | override fun login(email: String, password: String): UserLogged { 17 | if (email.isEmpty() || password.isEmpty()) 18 | throw RuntimeException() 19 | 20 | return UserLogged(email) 21 | } 22 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/repository/GitHubRepo.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.repository 2 | 3 | import com.example.networkmodule.api.api.GitHubService 4 | import com.example.networkmodule.api.model.Repo 5 | 6 | interface GitHubRepo { 7 | suspend fun getRepositoryByUser(user: String): List 8 | 9 | } 10 | 11 | class GitHubRepoImpl(private val api: GitHubService) : GitHubRepo { 12 | 13 | override suspend fun getRepositoryByUser(user: String): List { 14 | return api.listRepos(user) 15 | } 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/repository/model/UIUserLogged.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.repository.model 2 | 3 | 4 | data class UIUserLogged(var email: String = "") 5 | -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/repository/model/UserLogged.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.repository.model 2 | 3 | 4 | data class UserLogged(var username: String = "") 5 | -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/ui/GitHubActivity.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.ui 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import androidx.appcompat.app.AppCompatActivity 6 | import androidx.lifecycle.viewModelScope 7 | import com.sysdata.kt.ktandroidarchitecture.R 8 | import com.sysdata.kt.ktandroidarchitecture.usecase.GitHubActionParams 9 | import com.sysdata.kt.ktandroidarchitecture.viewmodel.GitHubViewModel 10 | import org.koin.androidx.viewmodel.ext.android.viewModel 11 | 12 | class GitHubActivity : AppCompatActivity() { 13 | private val viewModel by viewModel() 14 | 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | super.onCreate(savedInstanceState) 17 | setContentView(R.layout.activity_git_hub) 18 | viewModel.gitHubAction.observe(this) { 19 | Log.e("Repo", it.toString()) 20 | } 21 | viewModel.gitHubAction.execute(GitHubActionParams("SysdataSpA"), viewModel.viewModelScope) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/ui/LoginActivity.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.ui 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.text.Editable 6 | import android.text.TextWatcher 7 | import android.view.View 8 | import android.widget.Toast 9 | import androidx.fragment.app.FragmentActivity 10 | import com.sysdata.kt.ktandroidarchitecture.R 11 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UIUserLogged 12 | import com.sysdata.kt.ktandroidarchitecture.viewmodel.LoginViewModel 13 | import it.sysdata.ktandroidarchitecturecore.exception.Failure 14 | import kotlinx.android.synthetic.main.activity_login.* 15 | import org.koin.androidx.viewmodel.ext.android.viewModel 16 | 17 | class LoginActivity : FragmentActivity(), View.OnClickListener, TextWatcher { 18 | 19 | private val viewModel by viewModel() 20 | 21 | override fun onCreate(savedInstanceState: Bundle?) { 22 | super.onCreate(savedInstanceState) 23 | viewModel.actionLogin.observe(this, ::onUserLoggged) 24 | viewModel.actionLogin.observeFailure(this, ::onLoginFailed) 25 | 26 | setContentView(R.layout.activity_login) 27 | loginBtn.setOnClickListener(this) 28 | loginBtn.isEnabled = validateForm() 29 | 30 | usernameValue.addTextChangedListener(this) 31 | passwordValue.addTextChangedListener(this) 32 | } 33 | 34 | 35 | private fun onLoginFailed(failure: Failure?) { 36 | Toast.makeText(this, "failure : ${failure.toString()}", Toast.LENGTH_SHORT).show() 37 | } 38 | 39 | private fun onUserLoggged(userLogged: UIUserLogged?) { 40 | startActivity(Intent(this, GitHubActivity::class.java)) 41 | Toast.makeText(this, "user : ${userLogged?.email}", Toast.LENGTH_SHORT).show() 42 | } 43 | 44 | 45 | override fun onClick(p0: View?) { 46 | viewModel.login(usernameValue.text.toString(), passwordValue.text.toString()) 47 | } 48 | 49 | fun validateForm(): Boolean { 50 | return usernameValue.text.isNotEmpty() && passwordValue.text.isNotEmpty() && usernameValue.text.isNotBlank() && passwordValue.text.isNotBlank() 51 | } 52 | 53 | override fun afterTextChanged(p0: Editable?) { 54 | loginBtn.isEnabled = validateForm() 55 | } 56 | 57 | override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} 58 | 59 | override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} 60 | 61 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/usecase/GitHubUseCase.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.usecase 2 | 3 | import com.example.networkmodule.api.model.Repo 4 | import com.sysdata.kt.ktandroidarchitecture.repository.GitHubRepo 5 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UserLogged 6 | import it.sysdata.ktandroidarchitecturecore.exception.Failure 7 | import it.sysdata.ktandroidarchitecturecore.functional.Either 8 | import it.sysdata.ktandroidarchitecturecore.interactor.UseCase 9 | 10 | class GitHubUseCase(private val repo: GitHubRepo) : UseCase< List, GitHubActionParams>() { 11 | override suspend fun run(params: GitHubActionParams): Either> { 12 | return try { 13 | Either.Right(repo.getRepositoryByUser(params.user)) 14 | } catch (e: Exception) { 15 | Either.Left(Failure.NetworkConnection()) 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/usecase/LoginUseCase.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.usecase 2 | 3 | import com.sysdata.kt.ktandroidarchitecture.repository.AuthRepository 4 | import com.sysdata.kt.ktandroidarchitecture.repository.AuthRepositoryImpl 5 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UserLogged 6 | import it.sysdata.ktandroidarchitecturecore.exception.Failure 7 | import it.sysdata.ktandroidarchitecturecore.functional.Either 8 | import it.sysdata.ktandroidarchitecturecore.interactor.UseCase 9 | 10 | class LoginUseCase(private val repo:AuthRepository) : UseCase() { 11 | override suspend fun run(params: LoginActionParams): Either { 12 | return try { 13 | Either.Right(repo.login(params.email, params.password)) 14 | } catch (e: Exception) { 15 | Either.Left(Failure.NetworkConnection()) 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/usecase/Params.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.usecase 2 | 3 | import it.sysdata.ktandroidarchitecturecore.interactor.ActionParams 4 | 5 | class None : ActionParams() 6 | data class LoginActionParams(val email: String, val password: String) : ActionParams() 7 | 8 | data class GitHubActionParams(val user: String) : ActionParams() -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/viewmodel/GitHubViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.viewmodel 2 | 3 | import androidx.lifecycle.ViewModel 4 | import com.example.networkmodule.api.model.Repo 5 | import com.sysdata.kt.ktandroidarchitecture.usecase.GitHubActionParams 6 | import com.sysdata.kt.ktandroidarchitecture.usecase.GitHubUseCase 7 | import it.sysdata.ktandroidarchitecturecore.interactor.Action 8 | 9 | class GitHubViewModel(gitHubUseCase: GitHubUseCase) : ViewModel() { 10 | val gitHubAction = Action.Builder, List>() 11 | .useCase(gitHubUseCase) 12 | .buildWithUiModel { it } 13 | 14 | } -------------------------------------------------------------------------------- /app/src/main/java/com/sysdata/kt/ktandroidarchitecture/viewmodel/LoginViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.sysdata.kt.ktandroidarchitecture.viewmodel 2 | 3 | import androidx.lifecycle.viewModelScope 4 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UIUserLogged 5 | import com.sysdata.kt.ktandroidarchitecture.repository.model.UserLogged 6 | import com.sysdata.kt.ktandroidarchitecture.usecase.LoginActionParams 7 | import com.sysdata.kt.ktandroidarchitecture.usecase.LoginUseCase 8 | import it.sysdata.ktandroidarchitecturecore.interactor.Action 9 | import it.sysdata.ktandroidarchitecturecore.platform.BaseViewModel 10 | 11 | class LoginViewModel(loginUseCase: LoginUseCase) : BaseViewModel() { 12 | 13 | 14 | 15 | 16 | val actionLogin = Action.Builder() 17 | .useCase(loginUseCase) 18 | .buildWithUiModel { UIUserLogged(it.username) } 19 | 20 | 21 | fun login(username: String, password: String) { 22 | actionLogin.execute(LoginActionParams(username, password), viewModelScope) 23 | 24 | } 25 | 26 | 27 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_git_hub.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_login.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 | 21 | 22 | 28 | 29 | 34 | 35 |