├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── andreabresolin
│ │ └── androidcoroutinesplayground
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── andreabresolin
│ │ │ └── androidcoroutinesplayground
│ │ │ ├── MainActivity.kt
│ │ │ ├── app
│ │ │ ├── App.kt
│ │ │ ├── coroutines
│ │ │ │ ├── AppCoroutineScope.kt
│ │ │ │ ├── AppCoroutinesConfiguration.kt
│ │ │ │ ├── AppCoroutinesExtensions.kt
│ │ │ │ ├── AppCoroutinesHelpers.kt
│ │ │ │ └── testing
│ │ │ │ │ └── TestAppCoroutineScope.kt
│ │ │ ├── di
│ │ │ │ ├── ActivityBindingsModule.kt
│ │ │ │ ├── AppComponent.kt
│ │ │ │ ├── AppModule.kt
│ │ │ │ ├── FragmentBindingsModule.kt
│ │ │ │ └── scope
│ │ │ │ │ ├── PerActivity.kt
│ │ │ │ │ └── PerFragment.kt
│ │ │ ├── domain
│ │ │ │ ├── BaseUseCase.kt
│ │ │ │ └── task
│ │ │ │ │ ├── CallbackTaskUseCase.kt
│ │ │ │ │ ├── ChannelTaskUseCase.kt
│ │ │ │ │ ├── ExceptionsTaskUseCase.kt
│ │ │ │ │ ├── LongComputationTaskUseCase.kt
│ │ │ │ │ ├── MultipleTasksUseCase.kt
│ │ │ │ │ ├── ParallelErrorTaskUseCase.kt
│ │ │ │ │ ├── ParallelTaskUseCase.kt
│ │ │ │ │ ├── SequentialErrorTaskUseCase.kt
│ │ │ │ │ └── SequentialTaskUseCase.kt
│ │ │ ├── exception
│ │ │ │ └── CustomTaskException.kt
│ │ │ ├── model
│ │ │ │ ├── TaskExecutionResult.kt
│ │ │ │ └── TaskExecutionState.kt
│ │ │ ├── presentation
│ │ │ │ ├── BasePresenter.kt
│ │ │ │ └── BaseViewModel.kt
│ │ │ ├── repository
│ │ │ │ └── RemoteRepository.kt
│ │ │ ├── util
│ │ │ │ ├── DateTimeProvider.kt
│ │ │ │ └── LogUtil.kt
│ │ │ └── view
│ │ │ │ ├── BaseActivity.kt
│ │ │ │ └── BaseFragment.kt
│ │ │ ├── home
│ │ │ └── view
│ │ │ │ └── HomeFragment.kt
│ │ │ ├── mvp
│ │ │ ├── di
│ │ │ │ └── MVPModule.kt
│ │ │ ├── presenter
│ │ │ │ ├── MVPPresenter.kt
│ │ │ │ └── MVPPresenterImpl.kt
│ │ │ └── view
│ │ │ │ ├── MVPFragment.kt
│ │ │ │ └── MVPView.kt
│ │ │ └── mvvm
│ │ │ ├── di
│ │ │ └── MVVMModule.kt
│ │ │ ├── view
│ │ │ └── MVVMFragment.kt
│ │ │ └── viewmodel
│ │ │ ├── MVVMViewModel.kt
│ │ │ ├── MVVMViewModelFactory.kt
│ │ │ └── MVVMViewModelImpl.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── fragment_home.xml
│ │ ├── fragment_mvp.xml
│ │ ├── fragment_mvvm.xml
│ │ └── fragment_tasks_common.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
│ │ ├── navigation
│ │ └── activity_main_navigation.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── andreabresolin
│ └── androidcoroutinesplayground
│ ├── app
│ ├── coroutines
│ │ └── AppCoroutinesHelpersTest.kt
│ └── domain
│ │ └── task
│ │ ├── CallbackTaskUseCaseTest.kt
│ │ ├── ChannelTaskUseCaseTest.kt
│ │ ├── ExceptionsTaskUseCaseTest.kt
│ │ ├── LongComputationTaskUseCaseTest.kt
│ │ ├── MultipleTasksUseCaseTest.kt
│ │ ├── ParallelTaskUseCaseTest.kt
│ │ └── SequentialTaskUseCaseTest.kt
│ ├── mvp
│ └── presenter
│ │ └── MVPPresenterImplTest.kt
│ ├── mvvm
│ └── viewmodel
│ │ └── MVVMViewModelImplTest.kt
│ └── testing
│ ├── BaseMockitoTest.kt
│ ├── BasePresenterTest.kt
│ ├── BaseViewModelTest.kt
│ ├── KotlinTestUtils.kt
│ └── MockableDeferred.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | /projectFilesBackup/.idea/
10 |
--------------------------------------------------------------------------------
/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 2019 Andrea Bresolin
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.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Coroutines Playground
2 |
3 | Example that shows a possible way of structuring the code in an Android app by making use of [Kotlin coroutines](https://kotlinlang.org/docs/reference/coroutines.html).
4 |
5 | This is based on the stable version of coroutines.
6 |
7 | The example is provided with both MVP and MVVM architectures (making use of Clean Architecture as well).
8 |
9 | For more information on the ideas used in this source code, check the [Kotlin Coroutines in Android](https://medium.com/p/3937ae46c43b) series:
10 |
11 | * [Part 1: Introduction](https://medium.com/p/3937ae46c43b)
12 | * [Part 2: The basics](https://medium.com/p/20af01151627)
13 | * [Part 3: Coroutines in Android Studio](https://medium.com/p/32364831d8ac)
14 | * [Part 4: Running coroutines sequentially or in parallel](https://medium.com/p/183272a25644)
15 | * [Part 5: Coroutine cancellation](https://medium.com/p/64dcb60570f6)
16 | * [Part 6: Exception propagation](https://medium.com/p/483ed521374)
17 | * [Part 7: A small DSL for Android apps development](https://medium.com/p/65f65f85824d)
18 | * [Part 8: MVP and MVVM with Clean Architecture](https://medium.com/p/231aab849e44)
19 | * [Part 9: Combining multiple tasks with the operators on collections](https://medium.com/p/2e8621c6e46b)
20 | * [Part 10: Handling callbacks](https://medium.com/p/4aaa0e4132c9)
21 | * [Part 11: Channels](https://medium.com/p/1b53f8b5f61c)
22 | * [Part 12: Testing](https://medium.com/p/17e77d5df5f3)
23 |
24 | ## License
25 |
26 | ```
27 | Copyright 2019 Andrea Bresolin
28 |
29 | Licensed under the Apache License, Version 2.0 (the "License");
30 | you may not use this file except in compliance with the License.
31 | You may obtain a copy of the License at
32 |
33 | http://www.apache.org/licenses/LICENSE-2.0
34 |
35 | Unless required by applicable law or agreed to in writing, software
36 | distributed under the License is distributed on an "AS IS" BASIS,
37 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
38 | See the License for the specific language governing permissions and
39 | limitations under the License.
40 | ```
--------------------------------------------------------------------------------
/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 "andreabresolin.androidcoroutinesplayground"
10 | minSdkVersion 28
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-optimize.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | compileOptions {
23 | sourceCompatibility JavaVersion.VERSION_1_8
24 | targetCompatibility JavaVersion.VERSION_1_8
25 | }
26 | }
27 |
28 | ext {
29 | appcompat_version = '1.0.2'
30 | core_ktx_version = '1.0.1'
31 | dagger_version = '2.20'
32 | kotlin_coroutines_version = '1.2.1'
33 | lifecycle_version = '2.0.0'
34 | constraintlayout_version = '1.1.3'
35 | navigation_version = '1.0.0'
36 | paris_version = '1.2.1'
37 | timber_version = '4.7.1'
38 | junit_version = '4.12'
39 | mockito_version = '2.24.0'
40 | assertj_version = '3.11.1'
41 | architecture_core_testing_version = '1.1.0'
42 | test_runner_version = '1.1.1'
43 | espresso_core_version = '3.1.1'
44 | }
45 |
46 | dependencies {
47 | implementation fileTree(dir: 'libs', include: ['*.jar'])
48 |
49 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
50 | implementation "androidx.appcompat:appcompat:$appcompat_version"
51 | implementation "androidx.core:core-ktx:$core_ktx_version"
52 |
53 | // Dagger
54 | implementation "com.google.dagger:dagger:$dagger_version"
55 | implementation "com.google.dagger:dagger-android:$dagger_version"
56 | implementation "com.google.dagger:dagger-android-support:$dagger_version"
57 | kapt "com.google.dagger:dagger-compiler:$dagger_version"
58 | kapt "com.google.dagger:dagger-android-processor:$dagger_version"
59 |
60 | // Kotlin coroutines
61 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
62 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_coroutines_version"
63 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version"
64 |
65 | // Architecture Components: Lifecycle, LiveData, ViewModel
66 | implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
67 | kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
68 |
69 | // ConstraintLayout
70 | implementation "androidx.constraintlayout:constraintlayout:$constraintlayout_version"
71 |
72 | // Architecture Components: Navigation
73 | implementation "android.arch.navigation:navigation-fragment-ktx:$navigation_version"
74 | implementation "android.arch.navigation:navigation-ui-ktx:$navigation_version"
75 |
76 | // Paris
77 | implementation "com.airbnb.android:paris:$paris_version"
78 | kapt "com.airbnb.android:paris-processor:$paris_version"
79 |
80 | // Timber
81 | implementation "com.jakewharton.timber:timber:$timber_version"
82 |
83 | // JUnit
84 | testImplementation "junit:junit:$junit_version"
85 |
86 | // Mockito
87 | testImplementation "org.mockito:mockito-core:$mockito_version"
88 | testImplementation "org.mockito:mockito-inline:$mockito_version"
89 | androidTestImplementation "org.mockito:mockito-android:$mockito_version"
90 |
91 | // AssertJ
92 | testImplementation "org.assertj:assertj-core:$assertj_version"
93 |
94 | // Architecture Components: testing
95 | testImplementation "android.arch.core:core-testing:$architecture_core_testing_version"
96 |
97 | // Espresso
98 | androidTestImplementation "androidx.test:runner:$test_runner_version"
99 | androidTestImplementation "androidx.test.espresso:espresso-core:$espresso_core_version"
100 | }
101 |
--------------------------------------------------------------------------------
/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/androidTest/java/andreabresolin/androidcoroutinesplayground/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground
2 |
3 | import androidx.test.InstrumentationRegistry
4 | import androidx.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getTargetContext()
22 | assertEquals("andreabresolin.androidcoroutinesplayground", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.view.BaseActivity
4 | import android.os.Bundle
5 |
6 | class MainActivity : BaseActivity() {
7 |
8 | override fun onCreate(savedInstanceState: Bundle?) {
9 | super.onCreate(savedInstanceState)
10 | setContentView(R.layout.activity_main)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/App.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app
2 |
3 | import andreabresolin.androidcoroutinesplayground.BuildConfig
4 | import andreabresolin.androidcoroutinesplayground.app.di.DaggerAppComponent
5 | import android.app.Activity
6 | import android.app.Application
7 | import dagger.android.AndroidInjector
8 | import dagger.android.DispatchingAndroidInjector
9 | import dagger.android.HasActivityInjector
10 | import javax.inject.Inject
11 | import timber.log.Timber.DebugTree
12 | import timber.log.Timber
13 |
14 | class App : Application(), HasActivityInjector {
15 |
16 | @Inject
17 | internal lateinit var activityInjector: DispatchingAndroidInjector
18 |
19 | init {
20 | System.setProperty("kotlinx.coroutines.debug", if (BuildConfig.DEBUG) "on" else "off")
21 | }
22 |
23 | override fun onCreate() {
24 | super.onCreate()
25 |
26 | if (BuildConfig.DEBUG) {
27 | Timber.plant(DebugTree())
28 | }
29 |
30 | DaggerAppComponent.builder()
31 | .application(this)
32 | .build()
33 | .inject(this)
34 | }
35 |
36 | override fun activityInjector(): AndroidInjector = activityInjector
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/coroutines/AppCoroutineScope.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines
2 |
3 | import kotlinx.coroutines.CoroutineScope
4 | import kotlinx.coroutines.Job
5 | import javax.inject.Inject
6 | import kotlin.coroutines.CoroutineContext
7 |
8 | open class AppCoroutineScope
9 | @Inject constructor() : CoroutineScope {
10 |
11 | private val job = Job()
12 |
13 | override val coroutineContext: CoroutineContext
14 | get() = AppCoroutinesConfiguration.uiDispatcher + job
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/coroutines/AppCoroutinesConfiguration.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines
2 |
3 | import kotlinx.coroutines.CoroutineDispatcher
4 | import kotlinx.coroutines.Dispatchers
5 |
6 | class AppCoroutinesConfiguration {
7 |
8 | companion object {
9 | const val TEST_TIMEOUT: Long = 500L
10 |
11 | var uiDispatcher: CoroutineDispatcher = Dispatchers.Main
12 | var backgroundDispatcher: CoroutineDispatcher = Dispatchers.Default
13 | var ioDispatcher: CoroutineDispatcher = Dispatchers.IO
14 | var isDelayEnabled: Boolean = true
15 | var useTestTimeout: Boolean = false
16 | var isLoggingEnabled: Boolean = true
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/coroutines/AppCoroutinesExtensions.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startJob
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startTask
5 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startTaskAsync
6 | import kotlinx.coroutines.*
7 |
8 | fun CoroutineScope.uiJob(timeout: Long = 0L, block: suspend CoroutineScope.() -> Unit) {
9 | startJob(this, AppCoroutinesConfiguration.uiDispatcher, timeout, block)
10 | }
11 |
12 | fun CoroutineScope.backgroundJob(timeout: Long = 0L, block: suspend CoroutineScope.() -> Unit) {
13 | startJob(this, AppCoroutinesConfiguration.backgroundDispatcher, timeout, block)
14 | }
15 |
16 | fun CoroutineScope.ioJob(timeout: Long = 0L, block: suspend CoroutineScope.() -> Unit) {
17 | startJob(this, AppCoroutinesConfiguration.ioDispatcher, timeout, block)
18 | }
19 |
20 | suspend fun uiTask(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): T {
21 | return startTask(AppCoroutinesConfiguration.uiDispatcher, timeout, block)
22 | }
23 |
24 | suspend fun backgroundTask(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): T {
25 | return startTask(AppCoroutinesConfiguration.backgroundDispatcher, timeout, block)
26 | }
27 |
28 | suspend fun ioTask(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): T {
29 | return startTask(AppCoroutinesConfiguration.ioDispatcher, timeout, block)
30 | }
31 |
32 | fun CoroutineScope.uiTaskAsync(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): Deferred {
33 | return startTaskAsync(this, AppCoroutinesConfiguration.uiDispatcher, timeout, block)
34 | }
35 |
36 | fun CoroutineScope.backgroundTaskAsync(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): Deferred {
37 | return startTaskAsync(this, AppCoroutinesConfiguration.backgroundDispatcher, timeout, block)
38 | }
39 |
40 | fun CoroutineScope.ioTaskAsync(timeout: Long = 0L, block: suspend CoroutineScope.() -> T): Deferred {
41 | return startTaskAsync(this, AppCoroutinesConfiguration.ioDispatcher, timeout, block)
42 | }
43 |
44 | suspend fun delayTask(milliseconds: Long) {
45 | if (AppCoroutinesConfiguration.isDelayEnabled) {
46 | delay(milliseconds)
47 | }
48 | }
49 |
50 | suspend fun Deferred.awaitOrReturn(returnIfCancelled: T): T {
51 | return try {
52 | await()
53 | } catch (e: CancellationException) {
54 | returnIfCancelled
55 | }
56 | }
57 |
58 | suspend fun awaitAllOrCancel(vararg deferreds: Deferred): List {
59 | try {
60 | return awaitAll(*deferreds)
61 | } catch (e: Exception) {
62 | if (e !is CancellationException) {
63 | deferreds.forEach { if (it.isActive) it.cancel() }
64 | }
65 |
66 | throw e
67 | }
68 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/coroutines/AppCoroutinesHelpers.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.util.logCompleted
4 | import andreabresolin.androidcoroutinesplayground.app.util.logStarted
5 | import kotlinx.coroutines.*
6 | import java.util.concurrent.atomic.AtomicLong
7 | import kotlin.coroutines.CoroutineContext
8 |
9 | internal class AppCoroutinesHelpers {
10 |
11 | companion object {
12 | private enum class HelperType {
13 | JOB, TASK, TASK_ASYNC
14 | }
15 |
16 | private val loggingTaskId = AtomicLong(1L)
17 |
18 | private suspend fun executeBlock(
19 | parentScope: CoroutineScope,
20 | callerType: HelperType,
21 | coroutineContext: CoroutineContext,
22 | block: suspend CoroutineScope.() -> T
23 | ): T {
24 | if (AppCoroutinesConfiguration.isLoggingEnabled) {
25 | val taskId = loggingTaskId.getAndIncrement()
26 |
27 | val methodName = when (coroutineContext) {
28 | AppCoroutinesConfiguration.uiDispatcher -> "ui"
29 | AppCoroutinesConfiguration.backgroundDispatcher -> "background"
30 | AppCoroutinesConfiguration.ioDispatcher -> "io"
31 | else -> ""
32 | } + when (callerType) {
33 | HelperType.JOB -> "Job"
34 | HelperType.TASK -> "Task"
35 | HelperType.TASK_ASYNC -> "TaskAsync"
36 | } + "#$taskId"
37 |
38 | logStarted(methodName)
39 | val result = parentScope.block()
40 | logCompleted(methodName)
41 | return result
42 | } else {
43 | return parentScope.block()
44 | }
45 | }
46 |
47 | private fun computeTimeout(timeout: Long): Long {
48 | return if (AppCoroutinesConfiguration.useTestTimeout) {
49 | AppCoroutinesConfiguration.TEST_TIMEOUT
50 | } else {
51 | timeout
52 | }
53 | }
54 |
55 | fun startJob(
56 | parentScope: CoroutineScope,
57 | coroutineContext: CoroutineContext,
58 | timeout: Long = 0L,
59 | block: suspend CoroutineScope.() -> Unit
60 | ) {
61 | parentScope.launch(coroutineContext) {
62 | supervisorScope {
63 | if (timeout > 0L) {
64 | withTimeout(computeTimeout(timeout)) {
65 | executeBlock(this, HelperType.JOB, coroutineContext, block)
66 | }
67 | } else {
68 | executeBlock(this, HelperType.JOB, coroutineContext, block)
69 | }
70 | }
71 | }
72 | }
73 |
74 | suspend fun startTask(
75 | coroutineContext: CoroutineContext,
76 | timeout: Long = 0L,
77 | block: suspend CoroutineScope.() -> T
78 | ): T {
79 | return withContext(coroutineContext) {
80 | return@withContext if (timeout > 0L) {
81 | withTimeout(computeTimeout(timeout)) {
82 | executeBlock(this, HelperType.TASK, coroutineContext, block)
83 | }
84 | } else {
85 | executeBlock(this, HelperType.TASK, coroutineContext, block)
86 | }
87 | }
88 | }
89 |
90 | fun startTaskAsync(
91 | parentScope: CoroutineScope,
92 | coroutineContext: CoroutineContext,
93 | timeout: Long = 0L,
94 | block: suspend CoroutineScope.() -> T
95 | ): Deferred {
96 | return parentScope.async(coroutineContext) {
97 | return@async supervisorScope {
98 | return@supervisorScope if (timeout > 0L) {
99 | withTimeout(computeTimeout(timeout)) {
100 | executeBlock(this, HelperType.TASK_ASYNC, coroutineContext, block)
101 | }
102 | } else {
103 | executeBlock(this, HelperType.TASK_ASYNC, coroutineContext, block)
104 | }
105 | }
106 | }
107 | }
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/coroutines/testing/TestAppCoroutineScope.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines.testing
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutineScope
4 | import kotlinx.coroutines.Dispatchers
5 | import kotlinx.coroutines.Job
6 | import kotlinx.coroutines.cancelChildren
7 | import javax.inject.Inject
8 | import kotlin.coroutines.CoroutineContext
9 |
10 | class TestAppCoroutineScope
11 | @Inject constructor() : AppCoroutineScope() {
12 |
13 | private val job = Job()
14 |
15 | override val coroutineContext: CoroutineContext
16 | get() = Dispatchers.Unconfined + job
17 |
18 | fun cancelJobs() {
19 | coroutineContext.cancelChildren()
20 | }
21 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/ActivityBindingsModule.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di
2 |
3 | import andreabresolin.androidcoroutinesplayground.MainActivity
4 | import andreabresolin.androidcoroutinesplayground.app.di.scope.PerActivity
5 | import dagger.Module
6 | import dagger.android.AndroidInjectionModule
7 | import dagger.android.ContributesAndroidInjector
8 |
9 | @Module(includes = [AndroidInjectionModule::class])
10 | abstract class ActivityBindingsModule {
11 |
12 | @PerActivity
13 | @ContributesAndroidInjector
14 | abstract fun bindMainActivity(): MainActivity
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/AppComponent.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.App
4 | import android.app.Application
5 | import dagger.BindsInstance
6 | import dagger.Component
7 | import dagger.android.AndroidInjector
8 | import dagger.android.DaggerApplication
9 | import dagger.android.support.AndroidSupportInjectionModule
10 | import javax.inject.Singleton
11 |
12 | @Singleton
13 | @Component(
14 | modules = [
15 | AndroidSupportInjectionModule::class,
16 | AppModule::class,
17 | ActivityBindingsModule::class,
18 | FragmentBindingsModule::class
19 | ]
20 | )
21 | interface AppComponent : AndroidInjector {
22 |
23 | @Component.Builder
24 | interface Builder {
25 |
26 | @BindsInstance
27 | fun application(application: Application): Builder
28 |
29 | fun build(): AppComponent
30 | }
31 |
32 | fun inject(app: App)
33 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/AppModule.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di
2 |
3 | import dagger.Module
4 |
5 | @Module
6 | abstract class AppModule
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/FragmentBindingsModule.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.di.scope.PerFragment
4 | import andreabresolin.androidcoroutinesplayground.mvp.di.MVPModule
5 | import andreabresolin.androidcoroutinesplayground.mvp.view.MVPFragment
6 | import andreabresolin.androidcoroutinesplayground.mvvm.di.MVVMModule
7 | import andreabresolin.androidcoroutinesplayground.mvvm.view.MVVMFragment
8 | import dagger.Module
9 | import dagger.android.AndroidInjectionModule
10 | import dagger.android.ContributesAndroidInjector
11 |
12 | @Module(includes = [AndroidInjectionModule::class])
13 | abstract class FragmentBindingsModule {
14 |
15 | @PerFragment
16 | @ContributesAndroidInjector(modules = [MVPModule::class])
17 | abstract fun bindMVPFragment(): MVPFragment
18 |
19 | @PerFragment
20 | @ContributesAndroidInjector(modules = [MVVMModule::class])
21 | abstract fun bindMVVMFragment(): MVVMFragment
22 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/scope/PerActivity.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di.scope
2 |
3 | import javax.inject.Scope
4 |
5 | @Scope
6 | @Retention(AnnotationRetention.RUNTIME)
7 | annotation class PerActivity
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/di/scope/PerFragment.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.di.scope
2 |
3 | import javax.inject.Scope
4 |
5 | @Scope
6 | @Retention(AnnotationRetention.RUNTIME)
7 | annotation class PerFragment
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/BaseUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain
2 |
3 | abstract class BaseUseCase
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/CallbackTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTask
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
6 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
9 | import kotlinx.coroutines.CancellableContinuation
10 | import kotlinx.coroutines.suspendCancellableCoroutine
11 | import javax.inject.Inject
12 | import kotlin.coroutines.resume
13 | import kotlin.coroutines.resumeWithException
14 | import kotlin.random.Random
15 |
16 | class CallbackTaskUseCase
17 | @Inject constructor() : BaseUseCase() {
18 |
19 | private class ExecutorWithCallback {
20 |
21 | fun executeAction(
22 | input: String,
23 | successCallback: (Long) -> Unit,
24 | cancelCallback: () -> Unit,
25 | errorCallback: () -> Unit
26 | ) {
27 | when (input) {
28 | "SUCCESS" -> successCallback(10L)
29 | "CANCEL" -> cancelCallback()
30 | else -> errorCallback()
31 | }
32 | }
33 | }
34 |
35 | suspend fun execute(param: String): TaskExecutionResult = backgroundTask {
36 | val taskDuration = Random.nextLong(1000, 2000)
37 | delayTask(taskDuration)
38 |
39 | return@backgroundTask suspendCancellableCoroutine { continuation ->
40 | ExecutorWithCallback().executeAction(param,
41 | { result -> successCallback(result, continuation) },
42 | { cancelCallback(continuation) },
43 | { errorCallback(continuation) })
44 | }
45 | }
46 |
47 | private fun successCallback(result: Long, continuation: CancellableContinuation) {
48 | continuation.resume(TaskExecutionSuccess(result))
49 | }
50 |
51 | private fun cancelCallback(continuation: CancellableContinuation) {
52 | continuation.cancel()
53 | }
54 |
55 | private fun errorCallback(continuation: CancellableContinuation) {
56 | continuation.resumeWithException(CustomTaskException())
57 | }
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ChannelTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTaskAsync
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
6 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
8 | import andreabresolin.androidcoroutinesplayground.app.util.logIteration
9 | import kotlinx.coroutines.CoroutineScope
10 | import kotlinx.coroutines.Deferred
11 | import kotlinx.coroutines.channels.SendChannel
12 | import kotlinx.coroutines.selects.select
13 | import javax.inject.Inject
14 |
15 | class ChannelTaskUseCase
16 | @Inject constructor() : BaseUseCase() {
17 |
18 | fun executeAsync(
19 | parentScope: CoroutineScope,
20 | sendInterval: Long,
21 | sentItemsCount: Long,
22 | primaryChannel: SendChannel,
23 | backupChannel: SendChannel? = null
24 | ): Deferred = parentScope.backgroundTaskAsync {
25 | var iterationNumber = 1L
26 |
27 | while (iterationNumber <= sentItemsCount) {
28 | logIteration("ChannelTaskUseCase.executeAsync@$parentScope", iterationNumber)
29 | delayTask(sendInterval)
30 |
31 | if (backupChannel != null) {
32 | select {
33 | primaryChannel.onSend(iterationNumber) { }
34 | backupChannel.onSend(iterationNumber) { }
35 | }
36 | } else {
37 | primaryChannel.send(iterationNumber)
38 | }
39 |
40 | iterationNumber++
41 | }
42 |
43 | primaryChannel.close()
44 | backupChannel?.close()
45 |
46 | return@backgroundTaskAsync TaskExecutionSuccess(sentItemsCount)
47 | }
48 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ExceptionsTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.*
4 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
5 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
6 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
8 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
9 | import kotlinx.coroutines.CoroutineScope
10 | import kotlinx.coroutines.Deferred
11 | import javax.inject.Inject
12 | import kotlin.random.Random
13 |
14 | class ExceptionsTaskUseCase
15 | @Inject constructor(
16 | private val remoteRepository: RemoteRepository
17 | ) : BaseUseCase() {
18 |
19 | suspend fun execute(
20 | startDelay: Long,
21 | minDuration: Long,
22 | maxDuration: Long
23 | ): TaskExecutionResult = backgroundTask {
24 | delayTask(startDelay)
25 |
26 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
27 |
28 | delayTask(taskDuration)
29 |
30 | throw CustomTaskException("Error in ExceptionsTaskUseCase.execute()")
31 | }
32 |
33 | fun executeAsync(
34 | parentScope: CoroutineScope,
35 | startDelay: Long,
36 | minDuration: Long,
37 | maxDuration: Long
38 | ): Deferred = parentScope.backgroundTaskAsync {
39 | delayTask(startDelay)
40 |
41 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
42 |
43 | delayTask(taskDuration)
44 |
45 | throw CustomTaskException("Error in ExceptionsTaskUseCase.executeAsync()")
46 | }
47 |
48 | fun executeWithRepositoryAsync(
49 | parentScope: CoroutineScope,
50 | startDelay: Long,
51 | minDuration: Long,
52 | maxDuration: Long
53 | ): Deferred = parentScope.backgroundTaskAsync {
54 | delayTask(startDelay)
55 |
56 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
57 |
58 | val fetchedData1 = ioTaskAsync {
59 | delayTask(2000)
60 | remoteRepository.fetchDataWithException()
61 | }
62 |
63 | val fetchedData2 = ioTaskAsync {
64 | delayTask(5000)
65 | remoteRepository.fetchData(taskDuration)
66 | }
67 |
68 | delayTask(taskDuration)
69 |
70 | return@backgroundTaskAsync TaskExecutionSuccess(awaitAllOrCancel(fetchedData1, fetchedData2).sum())
71 | }
72 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/LongComputationTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTaskAsync
4 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
5 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
6 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
7 | import andreabresolin.androidcoroutinesplayground.app.util.DateTimeProvider
8 | import andreabresolin.androidcoroutinesplayground.app.util.logCancelled
9 | import andreabresolin.androidcoroutinesplayground.app.util.logIteration
10 | import kotlinx.coroutines.CancellationException
11 | import kotlinx.coroutines.CoroutineScope
12 | import kotlinx.coroutines.Deferred
13 | import kotlinx.coroutines.isActive
14 | import javax.inject.Inject
15 |
16 | class LongComputationTaskUseCase
17 | @Inject constructor(
18 | private val dateTimeProvider: DateTimeProvider
19 | ) : BaseUseCase() {
20 |
21 | fun executeAsync(
22 | parentScope: CoroutineScope,
23 | iterationDuration: Long,
24 | iterationsCount: Long,
25 | timeout: Long = 0L
26 | ): Deferred = parentScope.backgroundTaskAsync(timeout = timeout) {
27 | var iterationNumber = 1L
28 | var nextIterationTime = dateTimeProvider.currentTimeMillis()
29 |
30 | while (isActive && iterationNumber <= iterationsCount) {
31 | if (dateTimeProvider.currentTimeMillis() >= nextIterationTime) {
32 | logIteration("LongComputationTaskUseCase.executeAsync@$parentScope", iterationNumber)
33 | nextIterationTime += iterationDuration
34 | iterationNumber++
35 | }
36 | }
37 |
38 | if (!isActive) {
39 | logCancelled("LongComputationTaskUseCase.executeAsync@$parentScope")
40 | throw CancellationException()
41 | }
42 |
43 | return@backgroundTaskAsync TaskExecutionSuccess(iterationNumber - 1)
44 | }
45 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/MultipleTasksUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTask
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.coroutines.ioTask
6 | import andreabresolin.androidcoroutinesplayground.app.coroutines.ioTaskAsync
7 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
9 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
10 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
11 | import javax.inject.Inject
12 | import kotlin.random.Random
13 |
14 | class MultipleTasksUseCase
15 | @Inject constructor(
16 | private val remoteRepository: RemoteRepository
17 | ) : BaseUseCase() {
18 |
19 | suspend fun execute(param1: Long, param2: Long, param3: Long): TaskExecutionResult = backgroundTask {
20 | val taskDuration = Random.nextLong(1000, 2000)
21 | delayTask(taskDuration)
22 |
23 | val fetchedData: Long = arrayOf(param1, param2, param3)
24 | .map { ioTaskAsync { remoteRepository.fetchData(it) } }
25 | .map { it.await() }
26 | .map { ioTask { remoteRepository.fetchData(it) } }
27 | .sum()
28 |
29 | return@backgroundTask TaskExecutionSuccess(fetchedData)
30 | }
31 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ParallelErrorTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTaskAsync
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
6 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionError
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
9 | import kotlinx.coroutines.CoroutineScope
10 | import kotlinx.coroutines.Deferred
11 | import javax.inject.Inject
12 | import kotlin.random.Random
13 |
14 | class ParallelErrorTaskUseCase
15 | @Inject constructor() : BaseUseCase() {
16 |
17 | fun executeAsync(
18 | parentScope: CoroutineScope,
19 | startDelay: Long,
20 | minDuration: Long,
21 | maxDuration: Long
22 | ): Deferred = parentScope.backgroundTaskAsync {
23 | delayTask(startDelay)
24 |
25 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
26 | delayTask(taskDuration)
27 |
28 | return@backgroundTaskAsync TaskExecutionError(CustomTaskException())
29 | }
30 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ParallelTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTaskAsync
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.coroutines.ioTask
6 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
9 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
10 | import kotlinx.coroutines.CoroutineScope
11 | import kotlinx.coroutines.Deferred
12 | import javax.inject.Inject
13 | import kotlin.random.Random
14 |
15 | class ParallelTaskUseCase
16 | @Inject constructor(
17 | private val remoteRepository: RemoteRepository
18 | ) : BaseUseCase() {
19 |
20 | fun executeAsync(
21 | parentScope: CoroutineScope,
22 | startDelay: Long,
23 | minDuration: Long,
24 | maxDuration: Long
25 | ): Deferred = parentScope.backgroundTaskAsync {
26 | delayTask(startDelay)
27 |
28 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
29 |
30 | val fetchedData = ioTask { remoteRepository.fetchData(taskDuration) }
31 |
32 | delayTask(taskDuration)
33 |
34 | return@backgroundTaskAsync TaskExecutionSuccess(fetchedData)
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/SequentialErrorTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTask
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
6 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionError
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
9 | import javax.inject.Inject
10 | import kotlin.random.Random
11 |
12 | class SequentialErrorTaskUseCase
13 | @Inject constructor() : BaseUseCase() {
14 |
15 | suspend fun execute(
16 | startDelay: Long,
17 | minDuration: Long,
18 | maxDuration: Long
19 | ): TaskExecutionResult = backgroundTask {
20 | delayTask(startDelay)
21 |
22 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
23 | delayTask(taskDuration)
24 |
25 | return@backgroundTask TaskExecutionError(CustomTaskException())
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/domain/task/SequentialTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.backgroundTask
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.delayTask
5 | import andreabresolin.androidcoroutinesplayground.app.coroutines.ioTask
6 | import andreabresolin.androidcoroutinesplayground.app.domain.BaseUseCase
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
9 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
10 | import javax.inject.Inject
11 | import kotlin.random.Random
12 |
13 | class SequentialTaskUseCase
14 | @Inject constructor(
15 | private val remoteRepository: RemoteRepository
16 | ) : BaseUseCase() {
17 |
18 | suspend fun execute(
19 | startDelay: Long,
20 | minDuration: Long,
21 | maxDuration: Long
22 | ): TaskExecutionResult = backgroundTask {
23 | delayTask(startDelay)
24 |
25 | val taskDuration = Random.nextLong(minDuration, maxDuration + 1)
26 |
27 | val fetchedData = ioTask { remoteRepository.fetchData(taskDuration) }
28 |
29 | delayTask(taskDuration)
30 |
31 | return@backgroundTask TaskExecutionSuccess(fetchedData)
32 | }
33 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/exception/CustomTaskException.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.exception
2 |
3 | class CustomTaskException : Exception {
4 | constructor() : super()
5 | constructor(message: String) : super(message)
6 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/model/TaskExecutionResult.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.model
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
4 |
5 | sealed class TaskExecutionResult
6 | data class TaskExecutionSuccess(val result: Long) : TaskExecutionResult()
7 | data class TaskExecutionError(val exception: CustomTaskException) : TaskExecutionResult()
8 | object TaskExecutionCancelled : TaskExecutionResult()
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/model/TaskExecutionState.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.model
2 |
3 | enum class TaskExecutionState {
4 | INITIAL,
5 | RUNNING,
6 | COMPLETED,
7 | CANCELLED,
8 | ERROR
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/presentation/BasePresenter.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.presentation
2 |
3 | import kotlinx.coroutines.CoroutineScope
4 | import kotlinx.coroutines.cancelChildren
5 |
6 | abstract class BasePresenter
7 | constructor(private val coroutineScope: CoroutineScope) : CoroutineScope by coroutineScope {
8 |
9 | fun cancelJobs() {
10 | coroutineScope.coroutineContext.cancelChildren()
11 | }
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/presentation/BaseViewModel.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.presentation
2 |
3 | import androidx.lifecycle.ViewModel
4 | import kotlinx.coroutines.CoroutineScope
5 | import kotlinx.coroutines.cancelChildren
6 |
7 | abstract class BaseViewModel
8 | constructor(private val coroutineScope: CoroutineScope) : ViewModel(), CoroutineScope by coroutineScope {
9 |
10 | override fun onCleared() {
11 | coroutineScope.coroutineContext.cancelChildren()
12 | super.onCleared()
13 | }
14 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/repository/RemoteRepository.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.repository
2 |
3 | import java.io.IOException
4 | import javax.inject.Inject
5 | import javax.inject.Singleton
6 |
7 | @Singleton
8 | class RemoteRepository
9 | @Inject constructor() {
10 |
11 | fun fetchData(input: Long): Long {
12 | return input * 10
13 | }
14 |
15 | fun fetchDataWithException(): Long {
16 | throw IOException("Error while reading repository data")
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/util/DateTimeProvider.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.util
2 |
3 | import javax.inject.Inject
4 |
5 | class DateTimeProvider
6 | @Inject constructor() {
7 |
8 | fun currentTimeMillis() = System.currentTimeMillis()
9 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/util/LogUtil.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.util
2 |
3 | import timber.log.Timber
4 |
5 | fun logStarted(methodName: String) {
6 | Timber.d("[%s][%s] Started", methodName, Thread.currentThread().name)
7 | }
8 |
9 | fun logCompleted(methodName: String) {
10 | Timber.d("[%s][%s] Completed", methodName, Thread.currentThread().name)
11 | }
12 |
13 | fun logCancelled(methodName: String) {
14 | Timber.d("[%s][%s] Cancelled", methodName, Thread.currentThread().name)
15 | }
16 |
17 | fun logIteration(methodName: String, iterationNumber: Long) {
18 | Timber.d("[%s][%s] Iteration %s", methodName, Thread.currentThread().name, iterationNumber.toString())
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/view/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.view
2 |
3 | import android.os.Bundle
4 | import androidx.appcompat.app.AppCompatActivity
5 | import androidx.fragment.app.Fragment
6 | import dagger.android.AndroidInjection
7 | import dagger.android.AndroidInjector
8 | import dagger.android.DispatchingAndroidInjector
9 | import dagger.android.support.HasSupportFragmentInjector
10 | import javax.inject.Inject
11 |
12 | abstract class BaseActivity : AppCompatActivity(), HasSupportFragmentInjector {
13 |
14 | @Inject
15 | internal lateinit var fragmentInjector: DispatchingAndroidInjector
16 |
17 | override fun supportFragmentInjector(): AndroidInjector = fragmentInjector
18 |
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | AndroidInjection.inject(this)
21 | super.onCreate(savedInstanceState)
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/app/view/BaseFragment.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.view
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.fragment.app.Fragment
8 | import dagger.android.AndroidInjector
9 | import dagger.android.DispatchingAndroidInjector
10 | import dagger.android.support.AndroidSupportInjection
11 | import dagger.android.support.HasSupportFragmentInjector
12 | import javax.inject.Inject
13 |
14 | abstract class BaseFragment : Fragment(), HasSupportFragmentInjector {
15 |
16 | @Inject
17 | internal lateinit var fragmentInjector: DispatchingAndroidInjector
18 |
19 | override fun supportFragmentInjector(): AndroidInjector = fragmentInjector
20 |
21 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
22 | AndroidSupportInjection.inject(this)
23 | return null
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/home/view/HomeFragment.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.home.view
2 |
3 | import andreabresolin.androidcoroutinesplayground.R
4 | import andreabresolin.androidcoroutinesplayground.app.view.BaseFragment
5 | import android.os.Bundle
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.view.ViewGroup
9 | import androidx.navigation.findNavController
10 | import kotlinx.android.synthetic.main.fragment_home.*
11 |
12 | class HomeFragment : BaseFragment() {
13 |
14 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
15 | return inflater.inflate(R.layout.fragment_home, container, false)
16 | }
17 |
18 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
19 | super.onViewCreated(view, savedInstanceState)
20 | setUpListeners()
21 | }
22 |
23 | private fun setUpListeners() {
24 | mvpFragmentBtn.setOnClickListener { view -> view.findNavController().navigate(R.id.homeToMVPAction) }
25 | mvvmFragmentBtn.setOnClickListener { view -> view.findNavController().navigate(R.id.homeToMVVMAction) }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvp/di/MVPModule.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.di
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.di.scope.PerFragment
4 | import andreabresolin.androidcoroutinesplayground.mvp.presenter.MVPPresenter
5 | import andreabresolin.androidcoroutinesplayground.mvp.presenter.MVPPresenterImpl
6 | import andreabresolin.androidcoroutinesplayground.mvp.view.MVPFragment
7 | import andreabresolin.androidcoroutinesplayground.mvp.view.MVPView
8 | import dagger.Binds
9 | import dagger.Module
10 |
11 | @Module
12 | abstract class MVPModule {
13 |
14 | @PerFragment
15 | @Binds
16 | abstract fun bindMVPPresenter(mvpPresenter: MVPPresenterImpl): MVPPresenter
17 |
18 | @PerFragment
19 | @Binds
20 | abstract fun bindMVPView(mvpFragment: MVPFragment): MVPView
21 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvp/presenter/MVPPresenter.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.presenter
2 |
3 | interface MVPPresenter {
4 |
5 | fun runSequentialTasks()
6 |
7 | fun runParallelTasks()
8 |
9 | fun runSequentialTasksWithError()
10 |
11 | fun runParallelTasksWithError()
12 |
13 | fun runMultipleTasks()
14 |
15 | fun runCallbackTasksWithError()
16 |
17 | fun runLongComputationTasks()
18 |
19 | fun cancelLongComputationTask1()
20 |
21 | fun cancelLongComputationTask2()
22 |
23 | fun cancelLongComputationTask3()
24 |
25 | fun runLongComputationTasksWithTimeout()
26 |
27 | fun runChannelsTasks()
28 |
29 | fun runExceptionsTasks()
30 |
31 | fun cancelJobs()
32 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvp/presenter/MVPPresenterImpl.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.presenter
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.*
4 | import andreabresolin.androidcoroutinesplayground.app.domain.task.*
5 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
6 | import andreabresolin.androidcoroutinesplayground.app.model.*
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState.*
8 | import andreabresolin.androidcoroutinesplayground.app.presentation.BasePresenter
9 | import andreabresolin.androidcoroutinesplayground.mvp.view.MVPView
10 | import kotlinx.coroutines.CancellationException
11 | import kotlinx.coroutines.Deferred
12 | import kotlinx.coroutines.TimeoutCancellationException
13 | import kotlinx.coroutines.channels.Channel
14 | import java.io.IOException
15 | import javax.inject.Inject
16 |
17 | class MVPPresenterImpl
18 | @Inject constructor(
19 | appCoroutineScope: AppCoroutineScope,
20 | private val view: MVPView,
21 | private val sequentialTask1: SequentialTaskUseCase,
22 | private val sequentialTask2: SequentialTaskUseCase,
23 | private val sequentialTask3: SequentialTaskUseCase,
24 | private val parallelTask1: ParallelTaskUseCase,
25 | private val parallelTask2: ParallelTaskUseCase,
26 | private val parallelTask3: ParallelTaskUseCase,
27 | private val sequentialErrorTask: SequentialErrorTaskUseCase,
28 | private val parallelErrorTask: ParallelErrorTaskUseCase,
29 | private val multipleTasks1: MultipleTasksUseCase,
30 | private val multipleTasks2: MultipleTasksUseCase,
31 | private val multipleTasks3: MultipleTasksUseCase,
32 | private val callbackTask1: CallbackTaskUseCase,
33 | private val callbackTask2: CallbackTaskUseCase,
34 | private val callbackTask3: CallbackTaskUseCase,
35 | private val longComputationTask1: LongComputationTaskUseCase,
36 | private val longComputationTask2: LongComputationTaskUseCase,
37 | private val longComputationTask3: LongComputationTaskUseCase,
38 | private val channelTask1: ChannelTaskUseCase,
39 | private val channelTask2: ChannelTaskUseCase,
40 | private val channelTask3: ChannelTaskUseCase,
41 | private val exceptionsTask: ExceptionsTaskUseCase
42 | ) : BasePresenter(appCoroutineScope), MVPPresenter {
43 |
44 | private var longComputationTask1Deferred: Deferred? = null
45 | private var longComputationTask2Deferred: Deferred? = null
46 | private var longComputationTask3Deferred: Deferred? = null
47 |
48 | private fun processTaskResult(taskExecutionResult: TaskExecutionResult): TaskExecutionState {
49 | return when (taskExecutionResult) {
50 | is TaskExecutionSuccess -> COMPLETED
51 | is TaskExecutionCancelled -> CANCELLED
52 | is TaskExecutionError -> ERROR
53 | }
54 | }
55 |
56 | override fun runSequentialTasks() = uiJob {
57 | view.updateTaskExecutionState(1, INITIAL)
58 | view.updateTaskExecutionState(2, INITIAL)
59 | view.updateTaskExecutionState(3, INITIAL)
60 |
61 | delayTask(1000)
62 |
63 | view.updateTaskExecutionState(1, RUNNING)
64 | val task1Result: TaskExecutionResult = sequentialTask1.execute(100, 500, 1500)
65 | view.updateTaskExecutionState(1, processTaskResult(task1Result))
66 |
67 | view.updateTaskExecutionState(2, RUNNING)
68 | val task2Result: TaskExecutionResult = sequentialTask2.execute(300, 200, 2000)
69 | view.updateTaskExecutionState(2, processTaskResult(task2Result))
70 |
71 | view.updateTaskExecutionState(3, RUNNING)
72 | val task3Result: TaskExecutionResult = sequentialTask3.execute(200, 600, 1800)
73 | view.updateTaskExecutionState(3, processTaskResult(task3Result))
74 | }
75 |
76 | override fun runParallelTasks() = uiJob {
77 | view.updateTaskExecutionState(1, INITIAL)
78 | view.updateTaskExecutionState(2, INITIAL)
79 | view.updateTaskExecutionState(3, INITIAL)
80 |
81 | delayTask(1000)
82 |
83 | view.updateTaskExecutionState(1, RUNNING)
84 | val task1Result: Deferred = parallelTask1.executeAsync(this, 100, 500, 1500)
85 |
86 | view.updateTaskExecutionState(2, RUNNING)
87 | val task2Result: Deferred = parallelTask2.executeAsync(this, 300, 200, 2000)
88 |
89 | view.updateTaskExecutionState(3, RUNNING)
90 | val task3Result: Deferred = parallelTask3.executeAsync(this, 200, 600, 1800)
91 |
92 | view.updateTaskExecutionState(1, processTaskResult(task1Result.await()))
93 | view.updateTaskExecutionState(2, processTaskResult(task2Result.await()))
94 | view.updateTaskExecutionState(3, processTaskResult(task3Result.await()))
95 | }
96 |
97 | override fun runSequentialTasksWithError() = uiJob {
98 | view.updateTaskExecutionState(1, INITIAL)
99 | view.updateTaskExecutionState(2, INITIAL)
100 | view.updateTaskExecutionState(3, INITIAL)
101 |
102 | delayTask(1000)
103 |
104 | view.updateTaskExecutionState(1, RUNNING)
105 | val task1Result: TaskExecutionResult = sequentialTask1.execute(100, 500, 1500)
106 | view.updateTaskExecutionState(1, processTaskResult(task1Result))
107 |
108 | view.updateTaskExecutionState(2, RUNNING)
109 | val task2Result: TaskExecutionResult = sequentialErrorTask.execute(300, 200, 2000)
110 | view.updateTaskExecutionState(2, processTaskResult(task2Result))
111 |
112 | view.updateTaskExecutionState(3, RUNNING)
113 | val task3Result: TaskExecutionResult = sequentialTask3.execute(200, 600, 1800)
114 | view.updateTaskExecutionState(3, processTaskResult(task3Result))
115 | }
116 |
117 | override fun runParallelTasksWithError() = uiJob {
118 | view.updateTaskExecutionState(1, INITIAL)
119 | view.updateTaskExecutionState(2, INITIAL)
120 | view.updateTaskExecutionState(3, INITIAL)
121 |
122 | delayTask(1000)
123 |
124 | view.updateTaskExecutionState(1, RUNNING)
125 | val task1Result: Deferred = parallelTask1.executeAsync(this, 100, 500, 1500)
126 |
127 | view.updateTaskExecutionState(2, RUNNING)
128 | val task2Result: Deferred = parallelErrorTask.executeAsync(this, 300, 200, 2000)
129 |
130 | view.updateTaskExecutionState(3, RUNNING)
131 | val task3Result: Deferred = parallelTask3.executeAsync(this, 200, 600, 1800)
132 |
133 | view.updateTaskExecutionState(1, processTaskResult(task1Result.await()))
134 | view.updateTaskExecutionState(2, processTaskResult(task2Result.await()))
135 | view.updateTaskExecutionState(3, processTaskResult(task3Result.await()))
136 | }
137 |
138 | override fun runMultipleTasks() = uiJob {
139 | view.updateTaskExecutionState(1, INITIAL)
140 | view.updateTaskExecutionState(2, INITIAL)
141 | view.updateTaskExecutionState(3, INITIAL)
142 |
143 | delayTask(1000)
144 |
145 | view.updateTaskExecutionState(1, RUNNING)
146 | val task1Result: TaskExecutionResult = multipleTasks1.execute(1, 10, 100)
147 | view.updateTaskExecutionState(1, processTaskResult(task1Result))
148 |
149 | view.updateTaskExecutionState(2, RUNNING)
150 | val task2Result: TaskExecutionResult = multipleTasks2.execute(2, 20, 200)
151 | view.updateTaskExecutionState(2, processTaskResult(task2Result))
152 |
153 | view.updateTaskExecutionState(3, RUNNING)
154 | val task3Result: TaskExecutionResult = multipleTasks3.execute(3, 30, 300)
155 | view.updateTaskExecutionState(3, processTaskResult(task3Result))
156 | }
157 |
158 | override fun runCallbackTasksWithError() = uiJob {
159 | view.updateTaskExecutionState(1, INITIAL)
160 | view.updateTaskExecutionState(2, INITIAL)
161 | view.updateTaskExecutionState(3, INITIAL)
162 |
163 | delayTask(1000)
164 |
165 | view.updateTaskExecutionState(1, RUNNING)
166 | try {
167 | val task1Result: TaskExecutionResult = callbackTask1.execute("RANDOM STRING")
168 | view.updateTaskExecutionState(1, processTaskResult(task1Result))
169 | } catch (e: CustomTaskException) {
170 | view.updateTaskExecutionState(1, processTaskResult(TaskExecutionError(e)))
171 | }
172 |
173 | view.updateTaskExecutionState(2, RUNNING)
174 | val task2Result: TaskExecutionResult = callbackTask2.execute("SUCCESS")
175 | view.updateTaskExecutionState(2, processTaskResult(task2Result))
176 |
177 | view.updateTaskExecutionState(3, RUNNING)
178 | try {
179 | val task3Result: TaskExecutionResult = callbackTask3.execute("CANCEL")
180 | view.updateTaskExecutionState(3, processTaskResult(task3Result))
181 | } catch (e: CancellationException) {
182 | view.updateTaskExecutionState(3, processTaskResult(TaskExecutionCancelled))
183 | }
184 | }
185 |
186 | override fun runLongComputationTasks() {
187 | uiJob {
188 | view.updateTaskExecutionState(1, INITIAL)
189 | delayTask(1000)
190 | view.updateTaskExecutionState(1, RUNNING)
191 |
192 | longComputationTask1Deferred = longComputationTask1.executeAsync(this, 500, 10)
193 | longComputationTask1Deferred?.let {
194 | view.updateTaskExecutionState(1, processTaskResult(it.awaitOrReturn(TaskExecutionCancelled)))
195 | }
196 | }
197 |
198 | uiJob {
199 | view.updateTaskExecutionState(2, INITIAL)
200 | delayTask(1000)
201 | view.updateTaskExecutionState(2, RUNNING)
202 |
203 | longComputationTask2Deferred = longComputationTask2.executeAsync(this, 1000, 5)
204 | longComputationTask2Deferred?.let {
205 | view.updateTaskExecutionState(2, processTaskResult(it.awaitOrReturn(TaskExecutionCancelled)))
206 | }
207 | }
208 |
209 | uiJob {
210 | view.updateTaskExecutionState(3, INITIAL)
211 | delayTask(1000)
212 | view.updateTaskExecutionState(3, RUNNING)
213 |
214 | longComputationTask3Deferred = longComputationTask3.executeAsync(this, 300, 20)
215 | longComputationTask3Deferred?.let {
216 | view.updateTaskExecutionState(3, processTaskResult(it.awaitOrReturn(TaskExecutionCancelled)))
217 | }
218 | }
219 | }
220 |
221 | override fun cancelLongComputationTask1() {
222 | longComputationTask1Deferred?.cancel()
223 | }
224 |
225 | override fun cancelLongComputationTask2() {
226 | longComputationTask2Deferred?.cancel()
227 | }
228 |
229 | override fun cancelLongComputationTask3() {
230 | longComputationTask3Deferred?.cancel()
231 | }
232 |
233 | override fun runLongComputationTasksWithTimeout() {
234 | uiJob {
235 | view.updateTaskExecutionState(1, INITIAL)
236 | delayTask(1000)
237 | view.updateTaskExecutionState(1, RUNNING)
238 |
239 | val taskResult: Deferred = longComputationTask1.executeAsync(this, 500, 10, 4000)
240 | view.updateTaskExecutionState(1, processTaskResult(taskResult.awaitOrReturn(TaskExecutionCancelled)))
241 | }
242 |
243 | uiJob {
244 | view.updateTaskExecutionState(2, INITIAL)
245 | delayTask(1000)
246 | view.updateTaskExecutionState(2, RUNNING)
247 |
248 | try {
249 | uiTask(timeout = 3000) {
250 | val taskResult: Deferred = longComputationTask2.executeAsync(this, 1000, 5)
251 | view.updateTaskExecutionState(2, processTaskResult(taskResult.await()))
252 | }
253 | } catch (e: TimeoutCancellationException) {
254 | view.updateTaskExecutionState(2, processTaskResult(TaskExecutionCancelled))
255 | }
256 | }
257 |
258 | uiJob(timeout = 2000) {
259 | view.updateTaskExecutionState(3, INITIAL)
260 | delayTask(1000)
261 | view.updateTaskExecutionState(3, RUNNING)
262 |
263 | val taskResult: Deferred = longComputationTask3.executeAsync(this, 300, 20)
264 | view.updateTaskExecutionState(3, processTaskResult(taskResult.awaitOrReturn(TaskExecutionCancelled)))
265 | }
266 | }
267 |
268 | override fun runChannelsTasks() {
269 | uiJob {
270 | view.updateTaskExecutionState(1, INITIAL)
271 |
272 | val channel = Channel()
273 | val itemProcessingTime = 400L
274 |
275 | val taskResult: Deferred = channelTask1.executeAsync(this, 800, 10, channel)
276 |
277 | for (receivedItem in channel) {
278 | view.updateTaskExecutionState(1, RUNNING)
279 | backgroundTask { delayTask(itemProcessingTime) }
280 | view.updateTaskExecutionState(1, INITIAL)
281 | }
282 |
283 | view.updateTaskExecutionState(1, processTaskResult(taskResult.await()))
284 | }
285 |
286 | uiJob {
287 | try {
288 | view.updateTaskExecutionState(2, INITIAL)
289 |
290 | val channel = Channel()
291 | val itemProcessingTime = 1000L
292 |
293 | val taskResult: Deferred = channelTask2.executeAsync(this, 800, 10, channel)
294 |
295 | for (receivedItem in channel) {
296 | view.updateTaskExecutionState(2, RUNNING)
297 | backgroundTask { delayTask(itemProcessingTime) }
298 | view.updateTaskExecutionState(2, INITIAL)
299 | }
300 |
301 | view.updateTaskExecutionState(2, processTaskResult(taskResult.await()))
302 | } catch (e: CancellationException) {
303 | view.updateTaskExecutionState(2, processTaskResult(TaskExecutionCancelled))
304 | }
305 | }
306 |
307 | uiJob {
308 | view.updateTaskExecutionState(3, INITIAL)
309 |
310 | val primaryChannel = Channel()
311 | val backpressureChannel = Channel()
312 | val itemProcessingTime = 1500L
313 |
314 | val taskResult: Deferred = channelTask3.executeAsync(this, 500, 20, primaryChannel, backpressureChannel)
315 |
316 | val primaryHandler = backgroundTaskAsync {
317 | for (receivedItem in primaryChannel) {
318 | uiTask { view.updateTaskExecutionState(3, RUNNING) }
319 | delayTask(itemProcessingTime)
320 | uiTask { view.updateTaskExecutionState(3, INITIAL) }
321 | }
322 | }
323 |
324 | val backpressureHandler = backgroundTaskAsync {
325 | for (receivedItem in backpressureChannel) {
326 | uiTask { view.updateTaskExecutionState(3, ERROR) }
327 | }
328 | }
329 |
330 | primaryHandler.await()
331 | backpressureHandler.await()
332 | view.updateTaskExecutionState(3, processTaskResult(taskResult.await()))
333 | }
334 | }
335 |
336 | override fun runExceptionsTasks() = uiJob {
337 | view.updateTaskExecutionState(1, INITIAL)
338 | view.updateTaskExecutionState(2, INITIAL)
339 | view.updateTaskExecutionState(3, INITIAL)
340 |
341 | delayTask(1000)
342 |
343 | view.updateTaskExecutionState(1, RUNNING)
344 | try {
345 | val task1Result: TaskExecutionResult = exceptionsTask.execute(100, 500, 1500)
346 | view.updateTaskExecutionState(1, processTaskResult(task1Result))
347 | } catch (e: CustomTaskException) {
348 | view.updateTaskExecutionState(1, ERROR)
349 | }
350 |
351 | view.updateTaskExecutionState(2, RUNNING)
352 | val task2Result: Deferred = exceptionsTask.executeAsync(this, 300, 200, 2000)
353 |
354 | view.updateTaskExecutionState(3, RUNNING)
355 | val task3Result: Deferred = exceptionsTask.executeWithRepositoryAsync(this, 200, 600, 1800)
356 |
357 | try {
358 | view.updateTaskExecutionState(2, processTaskResult(task2Result.await()))
359 | } catch (e: CustomTaskException) {
360 | view.updateTaskExecutionState(2, ERROR)
361 | }
362 |
363 | try {
364 | view.updateTaskExecutionState(3, processTaskResult(task3Result.await()))
365 | } catch (e: IOException) {
366 | view.updateTaskExecutionState(3, ERROR)
367 | }
368 | }
369 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvp/view/MVPFragment.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.view
2 |
3 | import andreabresolin.androidcoroutinesplayground.R
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState
5 | import andreabresolin.androidcoroutinesplayground.app.view.BaseFragment
6 | import andreabresolin.androidcoroutinesplayground.mvp.presenter.MVPPresenter
7 | import android.os.Bundle
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import android.view.ViewGroup
11 | import com.airbnb.paris.extensions.style
12 | import kotlinx.android.synthetic.main.fragment_tasks_common.*
13 | import javax.inject.Inject
14 |
15 | class MVPFragment : BaseFragment(), MVPView {
16 |
17 | @Inject
18 | internal lateinit var presenter: MVPPresenter
19 |
20 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
21 | super.onCreateView(inflater, container, savedInstanceState)
22 | return inflater.inflate(R.layout.fragment_mvp, container, false)
23 | }
24 |
25 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
26 | super.onViewCreated(view, savedInstanceState)
27 | setUpListeners()
28 | }
29 |
30 | override fun onStop() {
31 | presenter.cancelJobs()
32 | super.onStop()
33 | }
34 |
35 | private fun setUpListeners() {
36 | runSequentialBtn.setOnClickListener { onRunSequentialBtnClicked() }
37 | runParallelBtn.setOnClickListener { onRunParallelBtnClicked() }
38 | runSequentialWithErrorBtn.setOnClickListener { onRunSequentialWithErrorBtnClicked() }
39 | runParallelWithErrorBtn.setOnClickListener { onRunParallelWithErrorBtnClicked() }
40 | runMultipleBtn.setOnClickListener { onRunMultipleBtnClicked() }
41 | runCallbackWithErrorBtn.setOnClickListener { onRunCallbackWithErrorBtnClicked() }
42 | runLongComputationBtn.setOnClickListener { onRunLongComputationBtnClicked() }
43 | cancelLongComputation1Btn.setOnClickListener { onCancelLongComputation1BtnClicked() }
44 | cancelLongComputation2Btn.setOnClickListener { onCancelLongComputation2BtnClicked() }
45 | cancelLongComputation3Btn.setOnClickListener { onCancelLongComputation3BtnClicked() }
46 | runLongComputationWithTimeoutBtn.setOnClickListener { onRunLongComputationWithTimeoutBtnClicked() }
47 | runChannelsBtn.setOnClickListener { onRunChannelsBtnClicked() }
48 | runExceptionsBtn.setOnClickListener { onRunExceptionsBtnClicked() }
49 | }
50 |
51 | private fun onRunSequentialBtnClicked() {
52 | presenter.runSequentialTasks()
53 | }
54 |
55 | private fun onRunParallelBtnClicked() {
56 | presenter.runParallelTasks()
57 | }
58 |
59 | private fun onRunSequentialWithErrorBtnClicked() {
60 | presenter.runSequentialTasksWithError()
61 | }
62 |
63 | private fun onRunParallelWithErrorBtnClicked() {
64 | presenter.runParallelTasksWithError()
65 | }
66 |
67 | private fun onRunMultipleBtnClicked() {
68 | presenter.runMultipleTasks()
69 | }
70 |
71 | private fun onRunCallbackWithErrorBtnClicked() {
72 | presenter.runCallbackTasksWithError()
73 | }
74 |
75 | private fun onRunLongComputationBtnClicked() {
76 | presenter.runLongComputationTasks()
77 | }
78 |
79 | private fun onCancelLongComputation1BtnClicked() {
80 | presenter.cancelLongComputationTask1()
81 | }
82 |
83 | private fun onCancelLongComputation2BtnClicked() {
84 | presenter.cancelLongComputationTask2()
85 | }
86 |
87 | private fun onCancelLongComputation3BtnClicked() {
88 | presenter.cancelLongComputationTask3()
89 | }
90 |
91 | private fun onRunLongComputationWithTimeoutBtnClicked() {
92 | presenter.runLongComputationTasksWithTimeout()
93 | }
94 |
95 | private fun onRunChannelsBtnClicked() {
96 | presenter.runChannelsTasks()
97 | }
98 |
99 | private fun onRunExceptionsBtnClicked() {
100 | presenter.runExceptionsTasks()
101 | }
102 |
103 | private fun applyTaskStyleForState(taskView: View, taskExecutionState: TaskExecutionState) {
104 | when (taskExecutionState) {
105 | TaskExecutionState.INITIAL -> taskView.style(R.style.TaskBoxInitialState)
106 | TaskExecutionState.RUNNING -> taskView.style(R.style.TaskBoxRunningState)
107 | TaskExecutionState.COMPLETED -> taskView.style(R.style.TaskBoxCompletedState)
108 | TaskExecutionState.CANCELLED -> taskView.style(R.style.TaskBoxCancelledState)
109 | TaskExecutionState.ERROR -> taskView.style(R.style.TaskBoxErrorState)
110 | }
111 | }
112 |
113 | override fun updateTaskExecutionState(taskNumber: Int, taskExecutionState: TaskExecutionState) {
114 | val taskView: View? = when (taskNumber) {
115 | 1 -> task1Box
116 | 2 -> task2Box
117 | 3 -> task3Box
118 | else -> null
119 | }
120 |
121 | taskView?.let { applyTaskStyleForState(it, taskExecutionState) }
122 | }
123 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvp/view/MVPView.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.view
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState
4 |
5 | interface MVPView {
6 |
7 | fun updateTaskExecutionState(taskNumber: Int, taskExecutionState: TaskExecutionState)
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvvm/di/MVVMModule.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvvm.di
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.di.scope.PerFragment
4 | import andreabresolin.androidcoroutinesplayground.mvvm.viewmodel.MVVMViewModelFactory
5 | import androidx.lifecycle.ViewModelProvider
6 | import dagger.Binds
7 | import dagger.Module
8 |
9 | @Module
10 | abstract class MVVMModule {
11 |
12 | @PerFragment
13 | @Binds
14 | abstract fun bindMVVMViewModelFactory(mvvmViewModelFactory: MVVMViewModelFactory): ViewModelProvider.Factory
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvvm/view/MVVMFragment.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvvm.view
2 |
3 | import andreabresolin.androidcoroutinesplayground.R
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState
5 | import andreabresolin.androidcoroutinesplayground.app.view.BaseFragment
6 | import andreabresolin.androidcoroutinesplayground.mvvm.viewmodel.MVVMViewModel
7 | import android.os.Bundle
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import android.view.ViewGroup
11 | import androidx.lifecycle.Observer
12 | import androidx.lifecycle.ViewModelProvider
13 | import androidx.lifecycle.ViewModelProviders
14 | import com.airbnb.paris.extensions.style
15 | import kotlinx.android.synthetic.main.fragment_tasks_common.*
16 | import javax.inject.Inject
17 |
18 | class MVVMFragment : BaseFragment() {
19 |
20 | @Inject
21 | internal lateinit var viewModelFactory: ViewModelProvider.Factory
22 |
23 | private lateinit var viewModel: MVVMViewModel
24 |
25 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
26 | super.onCreateView(inflater, container, savedInstanceState)
27 | return inflater.inflate(R.layout.fragment_mvvm, container, false)
28 | }
29 |
30 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
31 | super.onViewCreated(view, savedInstanceState)
32 | viewModel = ViewModelProviders.of(this, viewModelFactory).get(MVVMViewModel::class.java)
33 | observeViewState()
34 | setUpListeners()
35 | }
36 |
37 | private fun observeViewState() {
38 | viewModel.task1State.observe(this, task1StateObserver)
39 | viewModel.task2State.observe(this, task2StateObserver)
40 | viewModel.task3State.observe(this, task3StateObserver)
41 | }
42 |
43 | private fun setUpListeners() {
44 | runSequentialBtn.setOnClickListener { onRunSequentialBtnClicked() }
45 | runParallelBtn.setOnClickListener { onRunParallelBtnClicked() }
46 | runSequentialWithErrorBtn.setOnClickListener { onRunSequentialWithErrorBtnClicked() }
47 | runParallelWithErrorBtn.setOnClickListener { onRunParallelWithErrorBtnClicked() }
48 | runMultipleBtn.setOnClickListener { onRunMultipleBtnClicked() }
49 | runCallbackWithErrorBtn.setOnClickListener { onRunCallbackWithErrorBtnClicked() }
50 | runLongComputationBtn.setOnClickListener { onRunLongComputationBtnClicked() }
51 | cancelLongComputation1Btn.setOnClickListener { onCancelLongComputation1BtnClicked() }
52 | cancelLongComputation2Btn.setOnClickListener { onCancelLongComputation2BtnClicked() }
53 | cancelLongComputation3Btn.setOnClickListener { onCancelLongComputation3BtnClicked() }
54 | runLongComputationWithTimeoutBtn.setOnClickListener { onRunLongComputationWithTimeoutBtnClicked() }
55 | runChannelsBtn.setOnClickListener { onRunChannelsBtnClicked() }
56 | runExceptionsBtn.setOnClickListener { onRunExceptionsBtnClicked() }
57 | }
58 |
59 | private val task1StateObserver = Observer { newState -> applyTaskStyleForState(task1Box, newState) }
60 | private val task2StateObserver = Observer { newState -> applyTaskStyleForState(task2Box, newState) }
61 | private val task3StateObserver = Observer { newState -> applyTaskStyleForState(task3Box, newState) }
62 |
63 | private fun applyTaskStyleForState(taskView: View, taskExecutionState: TaskExecutionState) {
64 | when (taskExecutionState) {
65 | TaskExecutionState.INITIAL -> taskView.style(R.style.TaskBoxInitialState)
66 | TaskExecutionState.RUNNING -> taskView.style(R.style.TaskBoxRunningState)
67 | TaskExecutionState.COMPLETED -> taskView.style(R.style.TaskBoxCompletedState)
68 | TaskExecutionState.CANCELLED -> taskView.style(R.style.TaskBoxCancelledState)
69 | TaskExecutionState.ERROR -> taskView.style(R.style.TaskBoxErrorState)
70 | }
71 | }
72 |
73 | private fun onRunSequentialBtnClicked() {
74 | viewModel.runSequentialTasks()
75 | }
76 |
77 | private fun onRunParallelBtnClicked() {
78 | viewModel.runParallelTasks()
79 | }
80 |
81 | private fun onRunSequentialWithErrorBtnClicked() {
82 | viewModel.runSequentialTasksWithError()
83 | }
84 |
85 | private fun onRunParallelWithErrorBtnClicked() {
86 | viewModel.runParallelTasksWithError()
87 | }
88 |
89 | private fun onRunMultipleBtnClicked() {
90 | viewModel.runMultipleTasks()
91 | }
92 |
93 | private fun onRunCallbackWithErrorBtnClicked() {
94 | viewModel.runCallbackTasksWithError()
95 | }
96 |
97 | private fun onRunLongComputationBtnClicked() {
98 | viewModel.runLongComputationTasks()
99 | }
100 |
101 | private fun onCancelLongComputation1BtnClicked() {
102 | viewModel.cancelLongComputationTask1()
103 | }
104 |
105 | private fun onCancelLongComputation2BtnClicked() {
106 | viewModel.cancelLongComputationTask2()
107 | }
108 |
109 | private fun onCancelLongComputation3BtnClicked() {
110 | viewModel.cancelLongComputationTask3()
111 | }
112 |
113 | private fun onRunLongComputationWithTimeoutBtnClicked() {
114 | viewModel.runLongComputationTasksWithTimeout()
115 | }
116 |
117 | private fun onRunChannelsBtnClicked() {
118 | viewModel.runChannelsTasks()
119 | }
120 |
121 | private fun onRunExceptionsBtnClicked() {
122 | viewModel.runExceptionsTasks()
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvvm/viewmodel/MVVMViewModel.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvvm.viewmodel
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutineScope
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState
5 | import andreabresolin.androidcoroutinesplayground.app.presentation.BaseViewModel
6 | import androidx.lifecycle.LiveData
7 |
8 | abstract class MVVMViewModel
9 | constructor(appCoroutineScope: AppCoroutineScope) : BaseViewModel(appCoroutineScope) {
10 |
11 | abstract val task1State: LiveData
12 | abstract val task2State: LiveData
13 | abstract val task3State: LiveData
14 |
15 | abstract fun runSequentialTasks()
16 |
17 | abstract fun runParallelTasks()
18 |
19 | abstract fun runSequentialTasksWithError()
20 |
21 | abstract fun runParallelTasksWithError()
22 |
23 | abstract fun runMultipleTasks()
24 |
25 | abstract fun runCallbackTasksWithError()
26 |
27 | abstract fun runLongComputationTasks()
28 |
29 | abstract fun cancelLongComputationTask1()
30 |
31 | abstract fun cancelLongComputationTask2()
32 |
33 | abstract fun cancelLongComputationTask3()
34 |
35 | abstract fun runLongComputationTasksWithTimeout()
36 |
37 | abstract fun runChannelsTasks()
38 |
39 | abstract fun runExceptionsTasks()
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvvm/viewmodel/MVVMViewModelFactory.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvvm.viewmodel
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutineScope
4 | import andreabresolin.androidcoroutinesplayground.app.domain.task.*
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.ViewModelProvider
7 | import javax.inject.Inject
8 |
9 | class MVVMViewModelFactory
10 | @Inject constructor(
11 | private val appCoroutineScope: AppCoroutineScope,
12 | private val sequentialTask1: SequentialTaskUseCase,
13 | private val sequentialTask2: SequentialTaskUseCase,
14 | private val sequentialTask3: SequentialTaskUseCase,
15 | private val parallelTask1: ParallelTaskUseCase,
16 | private val parallelTask2: ParallelTaskUseCase,
17 | private val parallelTask3: ParallelTaskUseCase,
18 | private val sequentialErrorTask: SequentialErrorTaskUseCase,
19 | private val parallelErrorTask: ParallelErrorTaskUseCase,
20 | private val multipleTasks1: MultipleTasksUseCase,
21 | private val multipleTasks2: MultipleTasksUseCase,
22 | private val multipleTasks3: MultipleTasksUseCase,
23 | private val callbackTask1: CallbackTaskUseCase,
24 | private val callbackTask2: CallbackTaskUseCase,
25 | private val callbackTask3: CallbackTaskUseCase,
26 | private val longComputationTask1: LongComputationTaskUseCase,
27 | private val longComputationTask2: LongComputationTaskUseCase,
28 | private val longComputationTask3: LongComputationTaskUseCase,
29 | private val channelTask1: ChannelTaskUseCase,
30 | private val channelTask2: ChannelTaskUseCase,
31 | private val channelTask3: ChannelTaskUseCase,
32 | private val exceptionsTask: ExceptionsTaskUseCase
33 | ) : ViewModelProvider.Factory {
34 |
35 | @Suppress("UNCHECKED_CAST")
36 | override fun create(modelClass: Class): T {
37 | return MVVMViewModelImpl(
38 | appCoroutineScope,
39 | sequentialTask1,
40 | sequentialTask2,
41 | sequentialTask3,
42 | parallelTask1,
43 | parallelTask2,
44 | parallelTask3,
45 | sequentialErrorTask,
46 | parallelErrorTask,
47 | multipleTasks1,
48 | multipleTasks2,
49 | multipleTasks3,
50 | callbackTask1,
51 | callbackTask2,
52 | callbackTask3,
53 | longComputationTask1,
54 | longComputationTask2,
55 | longComputationTask3,
56 | channelTask1,
57 | channelTask2,
58 | channelTask3,
59 | exceptionsTask
60 | ) as T
61 | }
62 | }
--------------------------------------------------------------------------------
/app/src/main/java/andreabresolin/androidcoroutinesplayground/mvvm/viewmodel/MVVMViewModelImpl.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvvm.viewmodel
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.*
4 | import andreabresolin.androidcoroutinesplayground.app.domain.task.*
5 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
6 | import andreabresolin.androidcoroutinesplayground.app.model.*
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState.*
8 | import androidx.lifecycle.MutableLiveData
9 | import kotlinx.coroutines.*
10 | import kotlinx.coroutines.channels.Channel
11 | import java.io.IOException
12 |
13 | class MVVMViewModelImpl
14 | constructor(
15 | appCoroutineScope: AppCoroutineScope,
16 | private val sequentialTask1: SequentialTaskUseCase,
17 | private val sequentialTask2: SequentialTaskUseCase,
18 | private val sequentialTask3: SequentialTaskUseCase,
19 | private val parallelTask1: ParallelTaskUseCase,
20 | private val parallelTask2: ParallelTaskUseCase,
21 | private val parallelTask3: ParallelTaskUseCase,
22 | private val sequentialErrorTask: SequentialErrorTaskUseCase,
23 | private val parallelErrorTask: ParallelErrorTaskUseCase,
24 | private val multipleTasks1: MultipleTasksUseCase,
25 | private val multipleTasks2: MultipleTasksUseCase,
26 | private val multipleTasks3: MultipleTasksUseCase,
27 | private val callbackTask1: CallbackTaskUseCase,
28 | private val callbackTask2: CallbackTaskUseCase,
29 | private val callbackTask3: CallbackTaskUseCase,
30 | private val longComputationTask1: LongComputationTaskUseCase,
31 | private val longComputationTask2: LongComputationTaskUseCase,
32 | private val longComputationTask3: LongComputationTaskUseCase,
33 | private val channelTask1: ChannelTaskUseCase,
34 | private val channelTask2: ChannelTaskUseCase,
35 | private val channelTask3: ChannelTaskUseCase,
36 | private val exceptionsTask: ExceptionsTaskUseCase
37 | ) : MVVMViewModel(appCoroutineScope) {
38 |
39 | override val task1State = MutableLiveData()
40 | override val task2State = MutableLiveData()
41 | override val task3State = MutableLiveData()
42 |
43 | private var longComputationTask1Deferred: Deferred? = null
44 | private var longComputationTask2Deferred: Deferred? = null
45 | private var longComputationTask3Deferred: Deferred? = null
46 |
47 | private fun processTaskResult(taskExecutionResult: TaskExecutionResult): TaskExecutionState {
48 | return when (taskExecutionResult) {
49 | is TaskExecutionSuccess -> COMPLETED
50 | is TaskExecutionCancelled -> CANCELLED
51 | is TaskExecutionError -> ERROR
52 | }
53 | }
54 |
55 | override fun runSequentialTasks() = uiJob {
56 | task1State.value = INITIAL
57 | task2State.value = INITIAL
58 | task3State.value = INITIAL
59 |
60 | delayTask(1000)
61 |
62 | task1State.value = RUNNING
63 | val task1Result: TaskExecutionResult = sequentialTask1.execute(100, 500, 1500)
64 | task1State.value = processTaskResult(task1Result)
65 |
66 | task2State.value = RUNNING
67 | val task2Result: TaskExecutionResult = sequentialTask2.execute(300, 200, 2000)
68 | task2State.value = processTaskResult(task2Result)
69 |
70 | task3State.value = RUNNING
71 | val task3Result: TaskExecutionResult = sequentialTask3.execute(200, 600, 1800)
72 | task3State.value = processTaskResult(task3Result)
73 | }
74 |
75 | override fun runParallelTasks() = uiJob {
76 | task1State.value = INITIAL
77 | task2State.value = INITIAL
78 | task3State.value = INITIAL
79 |
80 | delayTask(1000)
81 |
82 | task1State.value = RUNNING
83 | val task1Result: Deferred = parallelTask1.executeAsync(this, 100, 500, 1500)
84 |
85 | task2State.value = RUNNING
86 | val task2Result: Deferred = parallelTask2.executeAsync(this, 300, 200, 2000)
87 |
88 | task3State.value = RUNNING
89 | val task3Result: Deferred = parallelTask3.executeAsync(this, 200, 600, 1800)
90 |
91 | task1State.value = processTaskResult(task1Result.await())
92 | task2State.value = processTaskResult(task2Result.await())
93 | task3State.value = processTaskResult(task3Result.await())
94 | }
95 |
96 | override fun runSequentialTasksWithError() = uiJob {
97 | task1State.value = INITIAL
98 | task2State.value = INITIAL
99 | task3State.value = INITIAL
100 |
101 | delayTask(1000)
102 |
103 | task1State.value = RUNNING
104 | val task1Result: TaskExecutionResult = sequentialTask1.execute(100, 500, 1500)
105 | task1State.value = processTaskResult(task1Result)
106 |
107 | task2State.value = RUNNING
108 | val task2Result: TaskExecutionResult = sequentialErrorTask.execute(300, 200, 2000)
109 | task2State.value = processTaskResult(task2Result)
110 |
111 | task3State.value = RUNNING
112 | val task3Result: TaskExecutionResult = sequentialTask3.execute(200, 600, 1800)
113 | task3State.value = processTaskResult(task3Result)
114 | }
115 |
116 | override fun runParallelTasksWithError() = uiJob {
117 | task1State.value = INITIAL
118 | task2State.value = INITIAL
119 | task3State.value = INITIAL
120 |
121 | delayTask(1000)
122 |
123 | task1State.value = RUNNING
124 | val task1Result: Deferred = parallelTask1.executeAsync(this, 100, 500, 1500)
125 |
126 | task2State.value = RUNNING
127 | val task2Result: Deferred = parallelErrorTask.executeAsync(this, 300, 200, 2000)
128 |
129 | task3State.value = RUNNING
130 | val task3Result: Deferred = parallelTask3.executeAsync(this, 200, 600, 1800)
131 |
132 | task1State.value = processTaskResult(task1Result.await())
133 | task2State.value = processTaskResult(task2Result.await())
134 | task3State.value = processTaskResult(task3Result.await())
135 | }
136 |
137 | override fun runMultipleTasks() = uiJob {
138 | task1State.value = INITIAL
139 | task2State.value = INITIAL
140 | task3State.value = INITIAL
141 |
142 | delayTask(1000)
143 |
144 | task1State.value = RUNNING
145 | val task1Result: TaskExecutionResult = multipleTasks1.execute(1, 10, 100)
146 | task1State.value = processTaskResult(task1Result)
147 |
148 | task2State.value = RUNNING
149 | val task2Result: TaskExecutionResult = multipleTasks2.execute(2, 20, 200)
150 | task2State.value = processTaskResult(task2Result)
151 |
152 | task3State.value = RUNNING
153 | val task3Result: TaskExecutionResult = multipleTasks3.execute(3, 30, 300)
154 | task3State.value = processTaskResult(task3Result)
155 | }
156 |
157 | override fun runCallbackTasksWithError() = uiJob {
158 | task1State.value = INITIAL
159 | task2State.value = INITIAL
160 | task3State.value = INITIAL
161 |
162 | delayTask(1000)
163 |
164 | task1State.value = RUNNING
165 | try {
166 | val task1Result: TaskExecutionResult = callbackTask1.execute("RANDOM STRING")
167 | task1State.value = processTaskResult(task1Result)
168 | } catch (e: CustomTaskException) {
169 | task1State.value = processTaskResult(TaskExecutionError(e))
170 | }
171 |
172 | task2State.value = RUNNING
173 | val task2Result: TaskExecutionResult = callbackTask2.execute("SUCCESS")
174 | task2State.value = processTaskResult(task2Result)
175 |
176 | task3State.value = RUNNING
177 | try {
178 | val task3Result: TaskExecutionResult = callbackTask3.execute("CANCEL")
179 | task3State.value = processTaskResult(task3Result)
180 | } catch (e: CancellationException) {
181 | task3State.value = processTaskResult(TaskExecutionCancelled)
182 | }
183 | }
184 |
185 | override fun runLongComputationTasks() {
186 | uiJob {
187 | task1State.value = INITIAL
188 | delayTask(1000)
189 | task1State.value = RUNNING
190 |
191 | longComputationTask1Deferred = longComputationTask1.executeAsync(this, 500, 10)
192 | longComputationTask1Deferred?.let {
193 | task1State.value = processTaskResult(it.awaitOrReturn(TaskExecutionCancelled))
194 | }
195 | }
196 |
197 | uiJob {
198 | task2State.value = INITIAL
199 | delayTask(1000)
200 | task2State.value = RUNNING
201 |
202 | longComputationTask2Deferred = longComputationTask2.executeAsync(this, 1000, 5)
203 | longComputationTask2Deferred?.let {
204 | task2State.value = processTaskResult(it.awaitOrReturn(TaskExecutionCancelled))
205 | }
206 | }
207 |
208 | uiJob {
209 | task3State.value = INITIAL
210 | delayTask(1000)
211 | task3State.value = RUNNING
212 |
213 | longComputationTask3Deferred = longComputationTask3.executeAsync(this, 300, 20)
214 | longComputationTask3Deferred?.let {
215 | task3State.value = processTaskResult(it.awaitOrReturn(TaskExecutionCancelled))
216 | }
217 | }
218 | }
219 |
220 | override fun cancelLongComputationTask1() {
221 | longComputationTask1Deferred?.cancel()
222 | }
223 |
224 | override fun cancelLongComputationTask2() {
225 | longComputationTask2Deferred?.cancel()
226 | }
227 |
228 | override fun cancelLongComputationTask3() {
229 | longComputationTask3Deferred?.cancel()
230 | }
231 |
232 | override fun runLongComputationTasksWithTimeout() {
233 | uiJob {
234 | task1State.value = INITIAL
235 | delayTask(1000)
236 | task1State.value = RUNNING
237 |
238 | val taskResult: Deferred = longComputationTask1.executeAsync(this, 500, 10, 4000)
239 | task1State.value = processTaskResult(taskResult.awaitOrReturn(TaskExecutionCancelled))
240 | }
241 |
242 | uiJob {
243 | task2State.value = INITIAL
244 | delayTask(1000)
245 | task2State.value = RUNNING
246 |
247 | try {
248 | uiTask(timeout = 3000) {
249 | val taskResult: Deferred = longComputationTask2.executeAsync(this, 1000, 5)
250 | task2State.value = processTaskResult(taskResult.await())
251 | }
252 | } catch (e: TimeoutCancellationException) {
253 | task2State.value = processTaskResult(TaskExecutionCancelled)
254 | }
255 | }
256 |
257 | uiJob(timeout = 2000) {
258 | task3State.value = INITIAL
259 | delayTask(1000)
260 | task3State.value = RUNNING
261 |
262 | val taskResult: Deferred = longComputationTask3.executeAsync(this, 300, 20)
263 | task3State.value = processTaskResult(taskResult.awaitOrReturn(TaskExecutionCancelled))
264 | }
265 | }
266 |
267 | override fun runChannelsTasks() {
268 | uiJob {
269 | task1State.value = INITIAL
270 |
271 | val channel = Channel()
272 | val itemProcessingTime = 400L
273 |
274 | val taskResult: Deferred = channelTask1.executeAsync(this, 800, 10, channel)
275 |
276 | for (receivedItem in channel) {
277 | task1State.value = RUNNING
278 | backgroundTask { delayTask(itemProcessingTime) }
279 | task1State.value = INITIAL
280 | }
281 |
282 | task1State.value = processTaskResult(taskResult.await())
283 | }
284 |
285 | uiJob {
286 | try {
287 | task2State.value = INITIAL
288 |
289 | val channel = Channel()
290 | val itemProcessingTime = 1000L
291 |
292 | val taskResult: Deferred = channelTask2.executeAsync(this, 800, 10, channel)
293 |
294 | for (receivedItem in channel) {
295 | task2State.value = RUNNING
296 | backgroundTask { delayTask(itemProcessingTime) }
297 | task2State.value = INITIAL
298 | }
299 |
300 | task2State.value = processTaskResult(taskResult.await())
301 | } catch (e: CancellationException) {
302 | task2State.value = CANCELLED
303 | }
304 | }
305 |
306 | uiJob {
307 | task3State.value = INITIAL
308 |
309 | val primaryChannel = Channel()
310 | val backpressureChannel = Channel()
311 | val itemProcessingTime = 1500L
312 |
313 | val taskResult: Deferred = channelTask3.executeAsync(this, 500, 20, primaryChannel, backpressureChannel)
314 |
315 | val primaryHandler = backgroundTaskAsync {
316 | for (receivedItem in primaryChannel) {
317 | task3State.postValue(RUNNING)
318 | delayTask(itemProcessingTime)
319 | task3State.postValue(INITIAL)
320 | }
321 | }
322 |
323 | val backpressureHandler = backgroundTaskAsync {
324 | for (receivedItem in backpressureChannel) {
325 | task3State.postValue(ERROR)
326 | }
327 | }
328 |
329 | primaryHandler.await()
330 | backpressureHandler.await()
331 | task3State.value = processTaskResult(taskResult.await())
332 | }
333 | }
334 |
335 | override fun runExceptionsTasks() = uiJob {
336 | task1State.value = INITIAL
337 | task2State.value = INITIAL
338 | task3State.value = INITIAL
339 |
340 | delayTask(1000)
341 |
342 | task1State.value = RUNNING
343 | try {
344 | val task1Result: TaskExecutionResult = exceptionsTask.execute(100, 500, 1500)
345 | task1State.value = processTaskResult(task1Result)
346 | } catch (e: CustomTaskException) {
347 | task1State.value = ERROR
348 | }
349 |
350 | task2State.value = RUNNING
351 | val task2Result: Deferred = exceptionsTask.executeAsync(this, 300, 200, 2000)
352 |
353 | task3State.value = RUNNING
354 | val task3Result: Deferred = exceptionsTask.executeWithRepositoryAsync(this, 200, 600, 1800)
355 |
356 | try {
357 | task2State.value = processTaskResult(task2Result.await())
358 | } catch (e: CustomTaskException) {
359 | task2State.value = ERROR
360 | }
361 |
362 | try {
363 | task3State.value = processTaskResult(task3Result.await())
364 | } catch (e: IOException) {
365 | task3State.value = ERROR
366 | }
367 | }
368 | }
--------------------------------------------------------------------------------
/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 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
22 |
24 |
26 |
28 |
30 |
32 |
34 |
36 |
38 |
40 |
42 |
44 |
46 |
48 |
50 |
52 |
54 |
56 |
58 |
60 |
62 |
64 |
66 |
68 |
70 |
72 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_home.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
20 |
21 |
29 |
30 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_mvp.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
20 |
21 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_mvvm.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
20 |
21 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_tasks_common.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
21 |
22 |
32 |
33 |
43 |
44 |
52 |
53 |
56 |
57 |
65 |
66 |
74 |
75 |
84 |
85 |
94 |
95 |
104 |
105 |
114 |
115 |
124 |
125 |
134 |
135 |
144 |
145 |
154 |
155 |
164 |
165 |
174 |
175 |
184 |
185 |
186 |
187 |
188 |
189 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/navigation/activity_main_navigation.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
12 |
15 |
18 |
19 |
24 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 32dp
4 |
5 | 8dp
6 | 8dp
7 |
8 | 16dp
9 |
10 | 18sp
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Android Coroutines Playground
3 |
4 | Task 1
5 | Task 2
6 | Task 3
7 |
8 | Sequential
9 | Parallel
10 | Seq + error
11 | Par + error
12 | Multiple
13 | Callback + error
14 | Long
15 | Cncl 1
16 | Cncl 2
17 | Cncl 3
18 | Timeout
19 | Channels
20 | Exceptions
21 |
22 | Go to MVP Fragment
23 | Go to MVVM Fragment
24 |
25 | Home Fragment
26 | MVP Fragment
27 | MVVM Fragment
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
21 |
22 |
25 |
26 |
29 |
30 |
33 |
34 |
37 |
38 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/coroutines/AppCoroutinesHelpersTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.coroutines
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startJob
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startTask
5 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesHelpers.Companion.startTaskAsync
6 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
7 | import kotlinx.coroutines.*
8 | import org.assertj.core.api.Assertions.assertThat
9 | import org.junit.Before
10 | import org.junit.Test
11 |
12 | class AppCoroutinesHelpersTest : BaseMockitoTest() {
13 |
14 | private class TestException(message: String) : Exception(message)
15 |
16 | private val trackedEvents = mutableListOf()
17 |
18 | @Before
19 | fun before() {
20 | trackedEvents.clear()
21 | }
22 |
23 | // region Test
24 |
25 | @Test
26 | fun `Async task exception cancels siblings`() = runBlocking {
27 | val job = Job()
28 | val coroutineScope = CoroutineScope(Dispatchers.Default + job)
29 |
30 | startJob(coroutineScope, coroutineScope.coroutineContext) {
31 | trackEvent("JOB_START")
32 |
33 | val deferred1 = startTaskAsync(this, Dispatchers.Default) {
34 | delay(100)
35 | trackEvent("TASK1_START")
36 | delay(1000)
37 | throw TestException("TASK1_EXCEPTION")
38 | }
39 |
40 | val deferred2 = startTaskAsync(this, Dispatchers.Default) {
41 | delay(1000)
42 | trackEvent("TASK2_START")
43 | delay(2000)
44 | trackEvent("TASK2_END")
45 | }
46 |
47 | try {
48 | awaitAllOrCancel(deferred1, deferred2)
49 | } catch (e: TestException) {
50 | trackEvent(e.message!!)
51 | }
52 |
53 | trackEvent("JOB_END")
54 | }
55 |
56 | job.children.forEach { it.join() }
57 |
58 | assertThatEventsSequenceIs(
59 | "JOB_START",
60 | "TASK1_START",
61 | "TASK2_START",
62 | "TASK1_EXCEPTION",
63 | "JOB_END"
64 | )
65 | }
66 |
67 | @Test
68 | fun `Async task exception doesn't cancel siblings`() = runBlocking {
69 | val job = Job()
70 | val coroutineScope = CoroutineScope(Dispatchers.Default + job)
71 |
72 | startJob(coroutineScope, coroutineScope.coroutineContext) {
73 | trackEvent("JOB_START")
74 |
75 | val deferred1 = startTaskAsync(this, Dispatchers.Default) {
76 | delay(100)
77 | trackEvent("TASK1_START")
78 | delay(1000)
79 | throw TestException("TASK1_EXCEPTION")
80 | }
81 |
82 | val deferred2 = startTaskAsync(this, Dispatchers.Default) {
83 | delay(1000)
84 | trackEvent("TASK2_START")
85 | delay(2000)
86 | trackEvent("TASK2_END")
87 | }
88 |
89 | try {
90 | deferred1.await()
91 | } catch (e: TestException) {
92 | trackEvent(e.message!!)
93 | }
94 |
95 | deferred2.await()
96 |
97 | trackEvent("JOB_END")
98 | }
99 |
100 | job.children.forEach { it.join() }
101 |
102 | assertThatEventsSequenceIs(
103 | "JOB_START",
104 | "TASK1_START",
105 | "TASK2_START",
106 | "TASK1_EXCEPTION",
107 | "TASK2_END",
108 | "JOB_END"
109 | )
110 | }
111 |
112 | @Test
113 | fun `Async tasks cancelled correctly`() = runBlocking {
114 | val job = Job()
115 | val coroutineScope = CoroutineScope(Dispatchers.Default + job)
116 |
117 | startJob(coroutineScope, coroutineScope.coroutineContext) {
118 | trackEvent("JOB_START")
119 |
120 | val deferred1 = startTaskAsync(this, Dispatchers.Default) {
121 | delay(100)
122 | trackEvent("TASK1_START")
123 | delay(2000)
124 | trackEvent("TASK1_END")
125 | }
126 |
127 | val deferred2 = startTaskAsync(this, Dispatchers.Default) {
128 | delay(500)
129 | trackEvent("TASK2_START")
130 | delay(2000)
131 | trackEvent("TASK2_END")
132 | }
133 |
134 | deferred1.await()
135 | deferred2.await()
136 |
137 | trackEvent("JOB_END")
138 | }
139 |
140 | startJob(testAppCoroutineScope, testAppCoroutineScope.coroutineContext) {
141 | delay(1000)
142 | job.cancelChildren()
143 | }
144 |
145 | job.children.forEach { it.join() }
146 |
147 | assertThatEventsSequenceIs(
148 | "JOB_START",
149 | "TASK1_START",
150 | "TASK2_START"
151 | )
152 | }
153 |
154 | @Test
155 | fun `Nested tasks cancelled correctly`() = runBlocking {
156 | val job = Job()
157 | val coroutineScope = CoroutineScope(Dispatchers.Default + job)
158 |
159 | startJob(coroutineScope, coroutineScope.coroutineContext) {
160 | trackEvent("JOB_START")
161 |
162 | val deferred1 = startTaskAsync(this, Dispatchers.Default) {
163 | delay(100)
164 | trackEvent("TASK1_START")
165 |
166 | val nestedDeferred11 = startTaskAsync(this, Dispatchers.Default) {
167 | delay(100)
168 | trackEvent("TASK1-1_START")
169 | delay(2000)
170 | trackEvent("TASK1-1_END")
171 | }
172 |
173 | startTask(Dispatchers.IO) {
174 | val nestedDeferred12 = startTaskAsync(this, Dispatchers.Default) {
175 | delay(300)
176 | trackEvent("TASK1-2_START")
177 | delay(2000)
178 | trackEvent("TASK1-2_END")
179 | }
180 |
181 | nestedDeferred12.await()
182 | }
183 |
184 | nestedDeferred11.await()
185 |
186 | delay(2000)
187 | trackEvent("TASK1_END")
188 | }
189 |
190 | val deferred2 = startTaskAsync(this, Dispatchers.Default) {
191 | delay(700)
192 | trackEvent("TASK2_START")
193 |
194 | val nestedDeferred21 = startTaskAsync(this, Dispatchers.Default) {
195 | delay(100)
196 | trackEvent("TASK2-1_START")
197 | delay(2000)
198 | trackEvent("TASK2-1_END")
199 | }
200 |
201 | startTask(Dispatchers.IO) {
202 | val nestedDeferred22 = startTaskAsync(this, Dispatchers.Default) {
203 | delay(300)
204 | trackEvent("TASK2-2_START")
205 | delay(2000)
206 | trackEvent("TASK2-2_END")
207 | }
208 |
209 | nestedDeferred22.await()
210 | }
211 |
212 | nestedDeferred21.await()
213 |
214 | delay(2000)
215 | trackEvent("TASK2_END")
216 | }
217 |
218 | deferred1.await()
219 | deferred2.await()
220 |
221 | trackEvent("JOB_END")
222 | }
223 |
224 | startJob(testAppCoroutineScope, testAppCoroutineScope.coroutineContext) {
225 | delay(1500)
226 | job.cancelChildren()
227 | }
228 |
229 | job.children.forEach { it.join() }
230 |
231 | assertThatEventsSequenceIs(
232 | "JOB_START",
233 | "TASK1_START",
234 | "TASK1-1_START",
235 | "TASK1-2_START",
236 | "TASK2_START",
237 | "TASK2-1_START",
238 | "TASK2-2_START"
239 | )
240 | }
241 |
242 | @Test
243 | fun `Exception propagated correctly in nested tasks`() = runBlocking {
244 | val job = Job()
245 | val coroutineScope = CoroutineScope(Dispatchers.Default + job)
246 |
247 | startJob(coroutineScope, coroutineScope.coroutineContext) {
248 | trackEvent("JOB_START")
249 |
250 | val deferred1 = startTaskAsync(this, Dispatchers.Default) {
251 | delay(100)
252 | trackEvent("TASK1_START")
253 |
254 | startTask(Dispatchers.IO) {
255 | val nestedDeferred11 = startTaskAsync(this, Dispatchers.Default) {
256 | delay(300)
257 | trackEvent("TASK1-1_START")
258 | delay(400)
259 | throw TestException("TASK1-1_EXCEPTION")
260 | }
261 |
262 | nestedDeferred11.await()
263 | }
264 | }
265 |
266 | val deferred2 = startTaskAsync(this, Dispatchers.Default) {
267 | delay(500)
268 | trackEvent("TASK2_START")
269 |
270 | val nestedDeferred21 = startTaskAsync(this, Dispatchers.Default) {
271 | delay(100)
272 | trackEvent("TASK2-1_START")
273 | delay(1000)
274 | throw TestException("TASK2-1_EXCEPTION")
275 | }
276 |
277 | val nestedDeferred22 = startTaskAsync(this, Dispatchers.Default) {
278 | delay(500)
279 | trackEvent("TASK2-2_START")
280 | delay(2000)
281 | trackEvent("TASK2-2_END")
282 | }
283 |
284 | nestedDeferred22.await()
285 | nestedDeferred21.await()
286 | }
287 |
288 | val deferred3 = startTaskAsync(this, Dispatchers.Default) {
289 | delay(3500)
290 | trackEvent("TASK3_START")
291 |
292 | val nestedDeferred31 = startTaskAsync(this, Dispatchers.Default) {
293 | delay(100)
294 | trackEvent("TASK3-1_START")
295 | delay(700)
296 | throw TestException("TASK3-1_EXCEPTION")
297 | }
298 |
299 | val nestedDeferred32 = startTaskAsync(this, Dispatchers.Default) {
300 | delay(300)
301 | trackEvent("TASK3-2_START")
302 | delay(2000)
303 | trackEvent("TASK3-2_END")
304 | }
305 |
306 | try {
307 | awaitAllOrCancel(nestedDeferred31, nestedDeferred32)
308 | } catch (e: TestException) {
309 | trackEvent(e.message!!)
310 | }
311 | }
312 |
313 | try {
314 | deferred1.await()
315 | } catch (e: TestException) {
316 | trackEvent(e.message!!)
317 | }
318 |
319 | try {
320 | deferred2.await()
321 | } catch (e: TestException) {
322 | trackEvent(e.message!!)
323 | }
324 |
325 | deferred3.await()
326 |
327 | trackEvent("JOB_END")
328 | }
329 |
330 | job.children.forEach { it.join() }
331 |
332 | assertThatEventsSequenceIs(
333 | "JOB_START",
334 | "TASK1_START",
335 | "TASK1-1_START",
336 | "TASK2_START",
337 | "TASK2-1_START",
338 | "TASK1-1_EXCEPTION",
339 | "TASK2-2_START",
340 | "TASK2-2_END",
341 | "TASK2-1_EXCEPTION",
342 | "TASK3_START",
343 | "TASK3-1_START",
344 | "TASK3-2_START",
345 | "TASK3-1_EXCEPTION",
346 | "JOB_END"
347 | )
348 | }
349 |
350 | // endregion Test
351 |
352 | // region Helper
353 |
354 | private fun trackEvent(event: String) {
355 | trackedEvents.add(event)
356 | }
357 |
358 | private fun assertThatEventsSequenceIs(vararg expectedEventsSequence: String) {
359 | assertThat(trackedEvents).isEqualTo(expectedEventsSequence.asList())
360 | }
361 |
362 | // endregion Helper
363 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/CallbackTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
5 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
6 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
7 | import kotlinx.coroutines.CancellationException
8 | import kotlinx.coroutines.runBlocking
9 | import org.assertj.core.api.Assertions.assertThat
10 | import org.junit.Before
11 | import org.junit.Test
12 |
13 | class CallbackTaskUseCaseTest : BaseMockitoTest() {
14 |
15 | private lateinit var subject: CallbackTaskUseCase
16 |
17 | private var actualExecuteResult: TaskExecutionResult? = null
18 | private var actualExecuteException: Exception? = null
19 |
20 | @Before
21 | fun before() {
22 | subject = CallbackTaskUseCase()
23 | actualExecuteResult = null
24 | actualExecuteException = null
25 | }
26 |
27 | // region Test
28 |
29 | @Test
30 | fun execute_executesTaskWithSuccess() {
31 | whenExecuteWith("SUCCESS")
32 | thenResultIs(TaskExecutionSuccess(10L))
33 | thenNoException()
34 | }
35 |
36 | @Test
37 | fun execute_executesTaskWithCancellation() {
38 | whenExecuteWith("CANCEL")
39 | thenResultIsNull()
40 | thenExceptionIsInstanceOf(CancellationException::class.java)
41 | }
42 |
43 | @Test
44 | fun execute_executesTaskWithError() {
45 | whenExecuteWith("ANOTHER INPUT")
46 | thenResultIsNull()
47 | thenExceptionIsInstanceOf(CustomTaskException::class.java)
48 | }
49 |
50 | // endregion Test
51 |
52 | // region When
53 |
54 | private fun whenExecuteWith(param: String) = runBlocking {
55 | try {
56 | actualExecuteResult = subject.execute(param)
57 | } catch (e: Exception) {
58 | actualExecuteException = e
59 | }
60 | }
61 |
62 | // endregion When
63 |
64 | // region Then
65 |
66 | private fun thenResultIs(result: TaskExecutionResult) {
67 | assertThat(actualExecuteResult).isEqualTo(result)
68 | }
69 |
70 | private fun thenResultIsNull() {
71 | assertThat(actualExecuteResult).isNull()
72 | }
73 |
74 | private fun thenExceptionIsInstanceOf(type: Class) {
75 | assertThat(actualExecuteException).isInstanceOf(type)
76 | }
77 |
78 | private fun thenNoException() {
79 | assertThat(actualExecuteException).isNull()
80 | }
81 |
82 | // endregion Then
83 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ChannelTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
5 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
6 | import kotlinx.coroutines.*
7 | import kotlinx.coroutines.channels.Channel
8 | import org.assertj.core.api.Assertions.assertThat
9 | import org.junit.Before
10 | import org.junit.Test
11 |
12 | class ChannelTaskUseCaseTest : BaseMockitoTest() {
13 |
14 | private lateinit var subject: ChannelTaskUseCase
15 |
16 | private lateinit var givenPrimaryChannel: Channel
17 | private var givenBackupChannel: Channel? = null
18 |
19 | private val actualPrimaryChannelItems = mutableListOf()
20 | private val actualBackupChannelItems = mutableListOf()
21 | private var actualExecuteAsyncResult: TaskExecutionResult? = null
22 |
23 | @Before
24 | fun before() {
25 | subject = ChannelTaskUseCase()
26 | }
27 |
28 | // region Test
29 |
30 | @Test
31 | fun executeAsync_sendsItemsOnPrimaryChannel() {
32 | givenPrimaryChannelIsAvailable()
33 | givenBackupChannelIsNotAvailable()
34 | whenExecuteAsyncWith(10)
35 | thenItemsSentOnPrimaryChannelAre(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
36 | thenResultIs(TaskExecutionSuccess(10))
37 | thenPrimaryChannelIsClosed()
38 | }
39 |
40 | @Test
41 | fun executeAsync_sendsItemsOnPrimaryAndBackupChannels() {
42 | givenPrimaryChannelIsAvailable()
43 | givenBackupChannelIsAvailable()
44 | whenExecuteAsyncWith(6, 4)
45 | thenItemsSentOnPrimaryChannelAre(1, 2, 3, 4, 5, 6)
46 | thenItemsSentOnBackupChannelAre(7, 8, 9, 10)
47 | thenResultIs(TaskExecutionSuccess(10))
48 | thenPrimaryChannelIsClosed()
49 | thenBackupChannelIsClosed()
50 | }
51 |
52 | // endregion Test
53 |
54 | // region Given
55 |
56 | private fun givenPrimaryChannelIsAvailable() {
57 | givenPrimaryChannel = Channel()
58 | }
59 |
60 | private fun givenBackupChannelIsAvailable() {
61 | givenBackupChannel = Channel()
62 | }
63 |
64 | private fun givenBackupChannelIsNotAvailable() {
65 | givenBackupChannel = null
66 | }
67 |
68 | // endregion Given
69 |
70 | // region When
71 |
72 | private fun whenExecuteAsyncWith(primaryChannelSentItemsCount: Long, backupChannelSentItemsCount: Long = 0L) = runBlocking {
73 | val primaryChannelConsumer = testAppCoroutineScope.async(Dispatchers.Default) {
74 | actualPrimaryChannelItems.clear()
75 |
76 | for (receivedItem in givenPrimaryChannel) {
77 | actualPrimaryChannelItems.add(receivedItem)
78 |
79 | if (backupChannelSentItemsCount > 0 && receivedItem == primaryChannelSentItemsCount) {
80 | break
81 | }
82 | }
83 | }
84 |
85 | var backupChannelConsumer: Deferred? = null
86 | givenBackupChannel?.let { backupChannel ->
87 | backupChannelConsumer = testAppCoroutineScope.async(Dispatchers.Default) {
88 | primaryChannelConsumer.await()
89 |
90 | actualBackupChannelItems.clear()
91 |
92 | for (receivedItem in backupChannel) {
93 | actualBackupChannelItems.add(receivedItem)
94 | }
95 | }
96 | }
97 |
98 | actualExecuteAsyncResult = subject.executeAsync(
99 | testAppCoroutineScope,
100 | 0L,
101 | primaryChannelSentItemsCount + backupChannelSentItemsCount,
102 | givenPrimaryChannel,
103 | givenBackupChannel).await()
104 |
105 | primaryChannelConsumer.await()
106 | backupChannelConsumer?.await()
107 | }
108 |
109 | // endregion When
110 |
111 | // region Then
112 |
113 | private fun thenItemsSentOnPrimaryChannelAre(vararg items: Long) {
114 | assertThat(actualPrimaryChannelItems).isEqualTo(items.asList())
115 | }
116 |
117 | private fun thenItemsSentOnBackupChannelAre(vararg items: Long) {
118 | assertThat(actualBackupChannelItems).isEqualTo(items.asList())
119 | }
120 |
121 | private fun thenResultIs(result: TaskExecutionResult) {
122 | assertThat(actualExecuteAsyncResult).isEqualTo(result)
123 | }
124 |
125 | private fun thenPrimaryChannelIsClosed() {
126 | assertThat(givenPrimaryChannel.isClosedForSend).isTrue()
127 | }
128 |
129 | private fun thenBackupChannelIsClosed() {
130 | assertThat(givenBackupChannel).isNotNull
131 | assertThat(givenBackupChannel?.isClosedForSend).isTrue()
132 | }
133 |
134 | // endregion Then
135 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ExceptionsTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
4 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
5 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
6 | import kotlinx.coroutines.runBlocking
7 | import org.assertj.core.api.Assertions.assertThat
8 | import org.junit.Before
9 | import org.junit.Test
10 | import org.mockito.ArgumentMatchers.anyLong
11 | import org.mockito.BDDMockito.given
12 | import org.mockito.Mock
13 | import java.io.IOException
14 |
15 | class ExceptionsTaskUseCaseTest : BaseMockitoTest() {
16 |
17 | @Mock
18 | private lateinit var mockRemoteRepository: RemoteRepository
19 |
20 | private lateinit var subject: ExceptionsTaskUseCase
21 |
22 | private lateinit var actualThrownException: Exception
23 |
24 | @Before
25 | fun before() {
26 | subject = ExceptionsTaskUseCase(mockRemoteRepository)
27 | }
28 |
29 | // region Test
30 |
31 | @Test
32 | fun execute_throwsCustomTaskException() {
33 | whenExecute()
34 | thenThrownExceptionIs(CustomTaskException::class.java)
35 | }
36 |
37 | @Test
38 | fun executeAsync_throwsCustomTaskException() {
39 | whenExecuteAsync()
40 | thenThrownExceptionIs(CustomTaskException::class.java)
41 | }
42 |
43 | @Test
44 | fun executeWithRepositoryAsync_throwsIOException() {
45 | givenDataWillBeFetchedFromRepository()
46 | whenExecuteWithRepositoryAsync()
47 | thenThrownExceptionIs(IOException::class.java)
48 | }
49 |
50 | // endregion Test
51 |
52 | // region Given
53 |
54 | private fun givenDataWillBeFetchedFromRepository() {
55 | given(mockRemoteRepository.fetchData(anyLong())).willReturn(0)
56 | given(mockRemoteRepository.fetchDataWithException()).willAnswer { throw IOException() }
57 | }
58 |
59 | // endregion Given
60 |
61 | // region When
62 |
63 | private fun whenExecute() = runBlocking {
64 | try {
65 | subject.execute(1L, 1L, 1L)
66 | } catch (e: Exception) {
67 | actualThrownException = e
68 | }
69 | }
70 |
71 | private fun whenExecuteAsync() = runBlocking {
72 | try {
73 | subject.executeAsync(testAppCoroutineScope, 1L, 1L, 1L).await()
74 | } catch (e: Exception) {
75 | actualThrownException = e
76 | }
77 | }
78 |
79 | private fun whenExecuteWithRepositoryAsync() = runBlocking {
80 | try {
81 | subject.executeWithRepositoryAsync(testAppCoroutineScope, 1L, 1L, 1L).await()
82 | } catch (e: Exception) {
83 | actualThrownException = e
84 | }
85 | }
86 |
87 | // endregion When
88 |
89 | // region Then
90 |
91 | private fun thenThrownExceptionIs(exception: Class) = runBlocking {
92 | assertThat(actualThrownException).isInstanceOf(exception)
93 | }
94 |
95 | // endregion Then
96 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/LongComputationTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesConfiguration.Companion.TEST_TIMEOUT
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
5 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
6 | import andreabresolin.androidcoroutinesplayground.app.util.DateTimeProvider
7 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
8 | import kotlinx.coroutines.CancellationException
9 | import kotlinx.coroutines.delay
10 | import kotlinx.coroutines.runBlocking
11 | import org.assertj.core.api.Assertions.assertThat
12 | import org.junit.Before
13 | import org.junit.Test
14 | import org.mockito.BDDMockito.*
15 | import org.mockito.Mock
16 |
17 | class LongComputationTaskUseCaseTest : BaseMockitoTest() {
18 |
19 | @Mock
20 | private lateinit var mockDateTimeProvider: DateTimeProvider
21 |
22 | private lateinit var subject: LongComputationTaskUseCase
23 |
24 | private var actualExecuteAsyncResult: TaskExecutionResult? = null
25 | private var actualExecuteAsyncException: Exception? = null
26 |
27 | @Before
28 | fun before() {
29 | actualExecuteAsyncResult = null
30 | actualExecuteAsyncException = null
31 |
32 | subject = LongComputationTaskUseCase(mockDateTimeProvider)
33 | }
34 |
35 | // region Test
36 |
37 | @Test
38 | fun executeAsync_executesTask() {
39 | givenExecuteAsyncWillHandleIterations(300, 10)
40 | whenExecuteAsyncWith(300, 10, 0)
41 | thenResultIs(TaskExecutionSuccess(10))
42 | thenIterationsCountIs(10)
43 | }
44 |
45 | @Test
46 | fun executeAsync_executesTaskUntilCancelled() {
47 | givenExecuteAsyncWillHandleIterationsAndThenBeCancelled(300, 5)
48 | whenExecuteAsyncWith(300, 10, 0)
49 | thenTaskCancelled()
50 | thenIterationsCountIs(5)
51 | }
52 |
53 | @Test
54 | fun executeAsync_executesTaskUntilTimeout() {
55 | givenExecuteAsyncWillHandleIterationsAndLastMoreThan(300, 5, TEST_TIMEOUT + 200L)
56 | whenExecuteAsyncWith(300, 10, TEST_TIMEOUT)
57 | thenTaskCancelled()
58 | thenIterationsCountIs(5)
59 | }
60 |
61 | // endregion Test
62 |
63 | // region Given
64 |
65 | private fun givenExecuteAsyncWillHandleIterations(iterationDuration: Int,
66 | iterationsCount: Int): BDDMyOngoingStubbing {
67 | var currentTime = 0L
68 | var ongoingStubbing = given(mockDateTimeProvider.currentTimeMillis()).willReturn(currentTime)
69 |
70 | repeat(iterationsCount) {
71 | ongoingStubbing = ongoingStubbing.willReturn(currentTime)
72 | currentTime += iterationDuration
73 | }
74 |
75 | return ongoingStubbing
76 | }
77 |
78 | private fun givenExecuteAsyncWillHandleIterationsAndThenBeCancelled(iterationDuration: Int,
79 | cancellationIterationNumber: Int) {
80 | givenExecuteAsyncWillHandleIterations(iterationDuration, cancellationIterationNumber - 1).willAnswer {
81 | testAppCoroutineScope.cancelJobs()
82 | return@willAnswer 0L
83 | }
84 | }
85 |
86 | private fun givenExecuteAsyncWillHandleIterationsAndLastMoreThan(iterationDuration: Int,
87 | iterationsCount: Int,
88 | minimumExecutionDuration: Long) {
89 | givenExecuteAsyncWillHandleIterations(iterationDuration, iterationsCount - 1).willAnswer {
90 | return@willAnswer runBlocking {
91 | delay(minimumExecutionDuration)
92 | return@runBlocking 0L
93 | }
94 | }
95 | }
96 |
97 | // endregion Given
98 |
99 | // region When
100 |
101 | private fun whenExecuteAsyncWith(iterationDuration: Long,
102 | iterationsCount: Long,
103 | timeout: Long) = runBlocking {
104 | try {
105 | actualExecuteAsyncResult = subject.executeAsync(testAppCoroutineScope, iterationDuration, iterationsCount, timeout).await()
106 | } catch (e: Exception) {
107 | actualExecuteAsyncException = e
108 | }
109 | }
110 |
111 | // endregion When
112 |
113 | // region Then
114 |
115 | private fun thenResultIs(result: TaskExecutionResult) {
116 | assertThat(actualExecuteAsyncResult).isEqualTo(result)
117 | }
118 |
119 | private fun thenTaskCancelled() {
120 | assertThat(actualExecuteAsyncException).isInstanceOf(CancellationException::class.java)
121 | }
122 |
123 | private fun thenIterationsCountIs(iterationsCount: Int) {
124 | then(mockDateTimeProvider).should(times(iterationsCount + 1)).currentTimeMillis()
125 | then(mockDateTimeProvider).shouldHaveNoMoreInteractions()
126 | }
127 |
128 | // endregion Then
129 | }
130 |
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/MultipleTasksUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
5 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
6 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
7 | import kotlinx.coroutines.runBlocking
8 | import org.assertj.core.api.Assertions.assertThat
9 | import org.junit.Before
10 | import org.junit.Test
11 | import org.mockito.BDDMockito.given
12 | import org.mockito.Mock
13 |
14 | class MultipleTasksUseCaseTest : BaseMockitoTest() {
15 |
16 | @Mock
17 | private lateinit var mockRemoteRepository: RemoteRepository
18 |
19 | private lateinit var subject: MultipleTasksUseCase
20 |
21 | private lateinit var actualExecuteResult: TaskExecutionResult
22 |
23 | @Before
24 | fun before() {
25 | subject = MultipleTasksUseCase(mockRemoteRepository)
26 | }
27 |
28 | // region Test
29 |
30 | @Test
31 | fun execute_executesTasks() {
32 | givenRemoteRepositoryWithInputWillReturn(1, 10)
33 | givenRemoteRepositoryWithInputWillReturn(2, 20)
34 | givenRemoteRepositoryWithInputWillReturn(3, 30)
35 | givenRemoteRepositoryWithInputWillReturn(10, 100)
36 | givenRemoteRepositoryWithInputWillReturn(20, 200)
37 | givenRemoteRepositoryWithInputWillReturn(30, 300)
38 | whenExecuteWith(1, 2, 3)
39 | thenResultIs(TaskExecutionSuccess(600))
40 | }
41 |
42 | // endregion Test
43 |
44 | // region Given
45 |
46 | private fun givenRemoteRepositoryWithInputWillReturn(input: Long, result: Long) {
47 | given(mockRemoteRepository.fetchData(input)).willReturn(result)
48 | }
49 |
50 | // endregion Given
51 |
52 | // region When
53 |
54 | private fun whenExecuteWith(param1: Long, param2: Long, param3: Long) = runBlocking {
55 | actualExecuteResult = subject.execute(param1, param2, param3)
56 | }
57 |
58 | // endregion When
59 |
60 | // region Then
61 |
62 | private fun thenResultIs(result: TaskExecutionResult) {
63 | assertThat(actualExecuteResult).isEqualTo(result)
64 | }
65 |
66 | // endregion Then
67 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/ParallelTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
5 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
6 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
7 | import kotlinx.coroutines.Deferred
8 | import kotlinx.coroutines.runBlocking
9 | import org.assertj.core.api.Assertions.assertThat
10 | import org.junit.Before
11 | import org.junit.Test
12 | import org.mockito.ArgumentMatchers.anyLong
13 | import org.mockito.BDDMockito.given
14 | import org.mockito.Mock
15 |
16 | class ParallelTaskUseCaseTest : BaseMockitoTest() {
17 |
18 | @Mock
19 | private lateinit var mockRemoteRepository: RemoteRepository
20 |
21 | private lateinit var subject: ParallelTaskUseCase
22 |
23 | private lateinit var actualExecuteAsyncResult: Deferred
24 |
25 | @Before
26 | fun before() {
27 | subject = ParallelTaskUseCase(mockRemoteRepository)
28 | }
29 |
30 | // region Test
31 |
32 | @Test
33 | fun executeAsync_executesTask() {
34 | givenFetchedDataIs(100)
35 | whenExecuteAsyncWith(10, 20, 30)
36 | thenResultIs(TaskExecutionSuccess(100))
37 | }
38 |
39 | // endregion Test
40 |
41 | // region Given
42 |
43 | private fun givenFetchedDataIs(result: Long) {
44 | given(mockRemoteRepository.fetchData(anyLong())).willReturn(result)
45 | }
46 |
47 | // endregion Given
48 |
49 | // region When
50 |
51 | private fun whenExecuteAsyncWith(startDelay: Long, minDuration: Long, maxDuration: Long) {
52 | actualExecuteAsyncResult = subject.executeAsync(testAppCoroutineScope, startDelay, minDuration, maxDuration)
53 | }
54 |
55 | // endregion When
56 |
57 | // region Then
58 |
59 | private fun thenResultIs(result: TaskExecutionResult) = runBlocking {
60 | assertThat(actualExecuteAsyncResult.await()).isEqualTo(result)
61 | }
62 |
63 | // endregion Then
64 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/app/domain/task/SequentialTaskUseCaseTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.app.domain.task
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
4 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
5 | import andreabresolin.androidcoroutinesplayground.app.repository.RemoteRepository
6 | import andreabresolin.androidcoroutinesplayground.testing.BaseMockitoTest
7 | import kotlinx.coroutines.runBlocking
8 | import org.assertj.core.api.Assertions.assertThat
9 | import org.junit.Before
10 | import org.junit.Test
11 | import org.mockito.BDDMockito.anyLong
12 | import org.mockito.BDDMockito.given
13 | import org.mockito.Mock
14 |
15 | class SequentialTaskUseCaseTest : BaseMockitoTest() {
16 |
17 | @Mock
18 | private lateinit var mockRemoteRepository: RemoteRepository
19 |
20 | private lateinit var subject: SequentialTaskUseCase
21 |
22 | private lateinit var actualExecuteResult: TaskExecutionResult
23 |
24 | @Before
25 | fun before() {
26 | subject = SequentialTaskUseCase(mockRemoteRepository)
27 | }
28 |
29 | // region Test
30 |
31 | @Test
32 | fun execute_executesTask() {
33 | givenRemoteRepositoryWillReturn(100)
34 | whenExecuteWith(10, 20, 30)
35 | thenResultIs(TaskExecutionSuccess(100))
36 | }
37 |
38 | // endregion Test
39 |
40 | // region Given
41 |
42 | private fun givenRemoteRepositoryWillReturn(result: Long) {
43 | given(mockRemoteRepository.fetchData(anyLong())).willReturn(result)
44 | }
45 |
46 | // endregion Given
47 |
48 | // region When
49 |
50 | private fun whenExecuteWith(startDelay: Long, minDuration: Long, maxDuration: Long) = runBlocking {
51 | actualExecuteResult = subject.execute(startDelay, minDuration, maxDuration)
52 | }
53 |
54 | // endregion When
55 |
56 | // region Then
57 |
58 | private fun thenResultIs(result: TaskExecutionResult) {
59 | assertThat(actualExecuteResult).isEqualTo(result)
60 | }
61 |
62 | // endregion Then
63 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/mvp/presenter/MVPPresenterImplTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.mvp.presenter
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.domain.task.*
4 | import andreabresolin.androidcoroutinesplayground.app.exception.CustomTaskException
5 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionError
6 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionResult
7 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState
8 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionState.*
9 | import andreabresolin.androidcoroutinesplayground.app.model.TaskExecutionSuccess
10 | import andreabresolin.androidcoroutinesplayground.mvp.view.MVPView
11 | import andreabresolin.androidcoroutinesplayground.testing.BasePresenterTest
12 | import andreabresolin.androidcoroutinesplayground.testing.KotlinTestUtils.Companion.anyObj
13 | import andreabresolin.androidcoroutinesplayground.testing.KotlinTestUtils.Companion.captureObj
14 | import andreabresolin.androidcoroutinesplayground.testing.MockableDeferred
15 | import kotlinx.coroutines.*
16 | import kotlinx.coroutines.channels.Channel
17 | import kotlinx.coroutines.channels.SendChannel
18 | import org.junit.Before
19 | import org.junit.Test
20 | import org.mockito.ArgumentCaptor
21 | import org.mockito.BDDMockito.given
22 | import org.mockito.BDDMockito.then
23 | import org.mockito.Mock
24 | import org.mockito.Mockito.*
25 | import java.io.IOException
26 |
27 | class MVPPresenterImplTest : BasePresenterTest() {
28 |
29 | @Mock
30 | private lateinit var mockView: MVPView
31 | @Mock
32 | private lateinit var mockSequentialTask1: SequentialTaskUseCase
33 | @Mock
34 | private lateinit var mockSequentialTask2: SequentialTaskUseCase
35 | @Mock
36 | private lateinit var mockSequentialTask3: SequentialTaskUseCase
37 | @Mock
38 | private lateinit var mockParallelTask1: ParallelTaskUseCase
39 | @Mock
40 | private lateinit var mockParallelTask2: ParallelTaskUseCase
41 | @Mock
42 | private lateinit var mockParallelTask3: ParallelTaskUseCase
43 | @Mock
44 | private lateinit var mockSequentialErrorTask: SequentialErrorTaskUseCase
45 | @Mock
46 | private lateinit var mockParallelErrorTask: ParallelErrorTaskUseCase
47 | @Mock
48 | private lateinit var mockMultipleTasks1: MultipleTasksUseCase
49 | @Mock
50 | private lateinit var mockMultipleTasks2: MultipleTasksUseCase
51 | @Mock
52 | private lateinit var mockMultipleTasks3: MultipleTasksUseCase
53 | @Mock
54 | private lateinit var mockCallbackTask1: CallbackTaskUseCase
55 | @Mock
56 | private lateinit var mockCallbackTask2: CallbackTaskUseCase
57 | @Mock
58 | private lateinit var mockCallbackTask3: CallbackTaskUseCase
59 | @Mock
60 | private lateinit var mockLongComputationTask1: LongComputationTaskUseCase
61 | @Mock
62 | private lateinit var mockLongComputationTask2: LongComputationTaskUseCase
63 | @Mock
64 | private lateinit var mockLongComputationTask3: LongComputationTaskUseCase
65 | @Mock
66 | private lateinit var mockLongComputationTask1Deferred: MockableDeferred
67 | @Mock
68 | private lateinit var mockLongComputationTask2Deferred: MockableDeferred
69 | @Mock
70 | private lateinit var mockLongComputationTask3Deferred: MockableDeferred
71 | @Mock
72 | private lateinit var mockChannelTask1: ChannelTaskUseCase
73 | @Mock
74 | private lateinit var mockChannelTask2: ChannelTaskUseCase
75 | @Mock
76 | private lateinit var mockChannelTask3: ChannelTaskUseCase
77 | @Mock
78 | private lateinit var mockChannelTask1Deferred: MockableDeferred
79 | @Mock
80 | private lateinit var mockChannelTask2Deferred: MockableDeferred
81 | @Mock
82 | private lateinit var mockChannelTask3Deferred: MockableDeferred
83 | @Mock
84 | private lateinit var mockExceptionsTask: ExceptionsTaskUseCase
85 | @Mock
86 | private lateinit var mockExceptionsTask2Deferred: MockableDeferred
87 | @Mock
88 | private lateinit var mockExceptionsTask3Deferred: MockableDeferred
89 |
90 | private lateinit var subject: MVPPresenterImpl
91 |
92 | private var givenChannel1Items = listOf()
93 | private var givenChannel2Items = listOf()
94 | private var givenChannel3Items = listOf()
95 | private var givenBackpressureChannel3Items = listOf()
96 |
97 | @Before
98 | fun before() {
99 | subject = MVPPresenterImpl(
100 | testAppCoroutineScope,
101 | mockView,
102 | mockSequentialTask1,
103 | mockSequentialTask2,
104 | mockSequentialTask3,
105 | mockParallelTask1,
106 | mockParallelTask2,
107 | mockParallelTask3,
108 | mockSequentialErrorTask,
109 | mockParallelErrorTask,
110 | mockMultipleTasks1,
111 | mockMultipleTasks2,
112 | mockMultipleTasks3,
113 | mockCallbackTask1,
114 | mockCallbackTask2,
115 | mockCallbackTask3,
116 | mockLongComputationTask1,
117 | mockLongComputationTask2,
118 | mockLongComputationTask3,
119 | mockChannelTask1,
120 | mockChannelTask2,
121 | mockChannelTask3,
122 | mockExceptionsTask)
123 | }
124 |
125 | // region Test
126 |
127 | @Test
128 | fun runSequentialTasks_runsSequentialTasksWithoutError() {
129 | givenThatSequentialTaskWillReturn(mockSequentialTask1, TaskExecutionSuccess(10))
130 | givenThatSequentialTaskWillReturn(mockSequentialTask2, TaskExecutionSuccess(20))
131 | givenThatSequentialTaskWillReturn(mockSequentialTask3, TaskExecutionSuccess(30))
132 | whenRunSequentialTasks()
133 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
134 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
135 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
136 | thenNoMoreInteractionsWithView()
137 | }
138 |
139 | @Test
140 | fun runParallelTasks_runsParallelTasksWithoutError() {
141 | givenThatParallelTaskWillReturn(mockParallelTask1, TaskExecutionSuccess(10))
142 | givenThatParallelTaskWillReturn(mockParallelTask2, TaskExecutionSuccess(20))
143 | givenThatParallelTaskWillReturn(mockParallelTask3, TaskExecutionSuccess(30))
144 | whenRunParallelTasks()
145 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
146 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
147 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
148 | thenNoMoreInteractionsWithView()
149 | }
150 |
151 | @Test
152 | fun runSequentialTasksWithError_runsSequentialTasksWithError() {
153 | givenThatSequentialTaskWillReturn(mockSequentialTask1, TaskExecutionSuccess(10))
154 | givenThatSequentialErrorTaskWillReturn(mockSequentialErrorTask, TaskExecutionError(CustomTaskException()))
155 | givenThatSequentialTaskWillReturn(mockSequentialTask3, TaskExecutionSuccess(30))
156 | whenRunSequentialTasksWithError()
157 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
158 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, ERROR))
159 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
160 | thenNoMoreInteractionsWithView()
161 | }
162 |
163 | @Test
164 | fun runParallelTasksWithError_runsParallelTasksWithError() {
165 | givenThatParallelTaskWillReturn(mockParallelTask1, TaskExecutionSuccess(10))
166 | givenThatParallelErrorTaskWillReturn(mockParallelErrorTask, TaskExecutionError(CustomTaskException()))
167 | givenThatParallelTaskWillReturn(mockParallelTask3, TaskExecutionSuccess(30))
168 | whenRunParallelTasksWithError()
169 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
170 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, ERROR))
171 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
172 | thenNoMoreInteractionsWithView()
173 | }
174 |
175 | @Test
176 | fun runMultipleTasks_runsMultipleTasksWithoutError() {
177 | givenThatMultipleTasksWillReturn(mockMultipleTasks1, TaskExecutionSuccess(10))
178 | givenThatMultipleTasksWillReturn(mockMultipleTasks2, TaskExecutionSuccess(20))
179 | givenThatMultipleTasksWillReturn(mockMultipleTasks3, TaskExecutionSuccess(30))
180 | whenRunMultipleTasks()
181 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
182 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
183 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
184 | thenNoMoreInteractionsWithView()
185 | }
186 |
187 | @Test
188 | fun runCallbackTasksWithError_runsCallbackTasksWithError() {
189 | givenThatCallbackTaskWillThrow(mockCallbackTask1, CustomTaskException())
190 | givenThatCallbackTaskWillReturn(mockCallbackTask2, TaskExecutionSuccess(10))
191 | givenThatCallbackTaskWillBeCancelled(mockCallbackTask3)
192 | whenRunCallbackTasksWithError()
193 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, ERROR))
194 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
195 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, CANCELLED))
196 | thenNoMoreInteractionsWithView()
197 | }
198 |
199 | @Test
200 | fun runLongComputationTasks_runsLongComputationTasksWithoutError() {
201 | givenThatLongComputationTask1WillReturn(TaskExecutionSuccess(10))
202 | givenThatLongComputationTask2WillReturn(TaskExecutionSuccess(20))
203 | givenThatLongComputationTask3WillReturn(TaskExecutionSuccess(30))
204 | whenRunLongComputationTasks()
205 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
206 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
207 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
208 | thenWaitForCompletionOfLongComputationTasks()
209 | thenNoMoreInteractionsWithView()
210 | }
211 |
212 | @Test
213 | fun cancelLongComputationTask2_cancelsLongComputationTask2BeforeCompletion() {
214 | givenThatLongComputationTask1WillReturn(TaskExecutionSuccess(10))
215 | givenThatLongComputationTask2WillBeCancelled()
216 | givenThatLongComputationTask3WillReturn(TaskExecutionSuccess(30))
217 | givenThatRunLongComputationTasksHasBeenCalled()
218 | whenCancelLongComputationTask2()
219 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
220 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, CANCELLED))
221 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
222 | thenWaitForCompletionOfLongComputationTasks()
223 | thenTaskIsCancelled(mockLongComputationTask2Deferred)
224 | thenNoMoreInteractionsWithView()
225 | }
226 |
227 | @Test
228 | fun runLongComputationTasksWithTimeout_completesLongComputationTasksIfFasterThanTimeout() {
229 | givenThatLongComputationTask1WillReturn(TaskExecutionSuccess(10))
230 | givenThatLongComputationTask2WillReturn(TaskExecutionSuccess(20))
231 | givenThatLongComputationTask3WillReturn(TaskExecutionSuccess(30))
232 | whenRunLongComputationTasksWithTimeout()
233 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, COMPLETED))
234 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, COMPLETED))
235 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, COMPLETED))
236 | thenWaitForCompletionOfLongComputationTasks()
237 | thenNoMoreInteractionsWithView()
238 | }
239 |
240 | @Test
241 | fun runLongComputationTasksWithTimeout_cancelsLongComputationTasksIfSlowerThanTimeout() {
242 | givenThatLongComputationTask1WillTimeout()
243 | givenThatLongComputationTask2WillTimeout()
244 | givenThatLongComputationTask3WillTimeout()
245 | whenRunLongComputationTasksWithTimeout()
246 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, CANCELLED))
247 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, CANCELLED))
248 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, CANCELLED))
249 | thenWaitForCompletionOfLongComputationTasks()
250 | thenNoMoreInteractionsWithView()
251 | }
252 |
253 | @Test
254 | fun runChannelsTasks_handlesAllItemsSentByChannelsTasks() {
255 | givenThatChannelTask1WillReturn(TaskExecutionSuccess(1))
256 | givenThatChannelTask2WillReturn(TaskExecutionSuccess(2))
257 | givenThatChannelTask3WillReturn(TaskExecutionSuccess(3))
258 | givenThatChannel1WillSend(listOf(10L, 20L, 30L, 40L, 50L))
259 | givenThatChannel2WillSend(listOf(100L, 200L, 300L))
260 | givenThatChannel3WillSend(listOf(1000L, 2000L, 3000L, 4000L))
261 | givenThatBackpressureChannel3WillSend(listOf(10000L, 20000L))
262 | whenRunChannelsTasks()
263 | thenTaskStatesSequenceIs(1,
264 | listOf(
265 | INITIAL,
266 | RUNNING, INITIAL,
267 | RUNNING, INITIAL,
268 | RUNNING, INITIAL,
269 | RUNNING, INITIAL,
270 | RUNNING, INITIAL,
271 | COMPLETED))
272 | thenTaskStatesSequenceIs(2,
273 | listOf(
274 | INITIAL,
275 | RUNNING, INITIAL,
276 | RUNNING, INITIAL,
277 | RUNNING, INITIAL,
278 | COMPLETED))
279 | thenTaskStatesSequenceIs(3,
280 | listOf(
281 | INITIAL,
282 | RUNNING, INITIAL,
283 | RUNNING, INITIAL,
284 | RUNNING, INITIAL,
285 | RUNNING, INITIAL,
286 | ERROR,
287 | ERROR,
288 | COMPLETED))
289 | thenWaitForCompletionOfChannelsTasks()
290 | thenNoMoreInteractionsWithView()
291 | }
292 |
293 | @Test
294 | fun runExceptionsTasks_runsExceptionsTasksWithError() {
295 | givenThatExceptionsTaskExecuteWillThrow(CustomTaskException::class.java)
296 | givenThatExceptionsTaskExecuteAsyncWillThrow(CustomTaskException::class.java)
297 | givenThatExceptionsTaskExecuteWithRepositoryAsyncWillThrow(IOException::class.java)
298 | whenRunExceptionsTasks()
299 | thenTaskStatesSequenceIs(1, listOf(INITIAL, RUNNING, ERROR))
300 | thenTaskStatesSequenceIs(2, listOf(INITIAL, RUNNING, ERROR))
301 | thenTaskStatesSequenceIs(3, listOf(INITIAL, RUNNING, ERROR))
302 | }
303 |
304 | // endregion Test
305 |
306 | // region Given
307 |
308 | private fun givenThatSequentialTaskWillReturn(sequentialTask: SequentialTaskUseCase,
309 | taskExecutionResult: TaskExecutionResult) = runBlocking {
310 | given(sequentialTask.execute(anyLong(), anyLong(), anyLong())).willReturn(taskExecutionResult)
311 | }
312 |
313 | private fun givenThatParallelTaskWillReturn(parallelTask: ParallelTaskUseCase,
314 | taskExecutionResult: TaskExecutionResult) = runBlocking {
315 | given(parallelTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(CompletableDeferred(taskExecutionResult))
316 | }
317 |
318 | private fun givenThatSequentialErrorTaskWillReturn(sequentialErrorTask: SequentialErrorTaskUseCase,
319 | taskExecutionResult: TaskExecutionResult) = runBlocking {
320 | given(sequentialErrorTask.execute(anyLong(), anyLong(), anyLong())).willReturn(taskExecutionResult)
321 | }
322 |
323 | private fun givenThatParallelErrorTaskWillReturn(parallelErrorTask: ParallelErrorTaskUseCase,
324 | taskExecutionResult: TaskExecutionResult) = runBlocking {
325 | given(parallelErrorTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(CompletableDeferred(taskExecutionResult))
326 | }
327 |
328 | private fun givenThatMultipleTasksWillReturn(multipleTasks: MultipleTasksUseCase,
329 | taskExecutionResult: TaskExecutionResult) = runBlocking {
330 | given(multipleTasks.execute(anyLong(), anyLong(), anyLong())).willReturn(taskExecutionResult)
331 | }
332 |
333 | private fun givenThatCallbackTaskWillReturn(callbackTask: CallbackTaskUseCase,
334 | taskExecutionResult: TaskExecutionResult) = runBlocking {
335 | given(callbackTask.execute(anyString())).willReturn(taskExecutionResult)
336 | }
337 |
338 | private fun givenThatCallbackTaskWillThrow(callbackTask: CallbackTaskUseCase,
339 | exception: Exception) = runBlocking {
340 | given(callbackTask.execute(anyString())).willAnswer { throw exception }
341 | }
342 |
343 | private fun givenThatCallbackTaskWillBeCancelled(callbackTask: CallbackTaskUseCase) = runBlocking {
344 | given(callbackTask.execute(anyString())).willThrow(CancellationException())
345 | }
346 |
347 | private fun givenThatLongComputationTaskWillReturn(longComputationTask: LongComputationTaskUseCase,
348 | taskExecutionDeferred: Deferred,
349 | taskExecutionResult: TaskExecutionResult) = runBlocking {
350 | given(taskExecutionDeferred.await()).willReturn(taskExecutionResult)
351 | given(longComputationTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(taskExecutionDeferred)
352 | }
353 |
354 | private fun givenThatLongComputationTask1WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
355 | givenThatLongComputationTaskWillReturn(mockLongComputationTask1, mockLongComputationTask1Deferred, taskExecutionResult)
356 | }
357 |
358 | private fun givenThatLongComputationTask2WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
359 | givenThatLongComputationTaskWillReturn(mockLongComputationTask2, mockLongComputationTask2Deferred, taskExecutionResult)
360 | }
361 |
362 | private fun givenThatLongComputationTask3WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
363 | givenThatLongComputationTaskWillReturn(mockLongComputationTask3, mockLongComputationTask3Deferred, taskExecutionResult)
364 | }
365 |
366 | private fun givenThatLongComputationTaskWillBeCancelled(longComputationTask: LongComputationTaskUseCase,
367 | taskExecutionDeferred: Deferred) = runBlocking {
368 | given(longComputationTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(taskExecutionDeferred)
369 | given(taskExecutionDeferred.await()).willThrow(CancellationException())
370 | }
371 |
372 | private fun givenThatLongComputationTask2WillBeCancelled() = runBlocking {
373 | givenThatLongComputationTaskWillBeCancelled(mockLongComputationTask2, mockLongComputationTask2Deferred)
374 | }
375 |
376 | private fun givenThatRunLongComputationTasksHasBeenCalled() {
377 | whenRunLongComputationTasks()
378 | }
379 |
380 | private fun givenThatLongComputationTaskWillTimeout(longComputationTask: LongComputationTaskUseCase,
381 | taskExecutionDeferred: Deferred) = runBlocking {
382 | given(longComputationTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(taskExecutionDeferred)
383 | given(taskExecutionDeferred.await()).willThrow(mock(TimeoutCancellationException::class.java))
384 | }
385 |
386 | private fun givenThatLongComputationTask1WillTimeout() {
387 | givenThatLongComputationTaskWillTimeout(mockLongComputationTask1, mockLongComputationTask1Deferred)
388 | }
389 |
390 | private fun givenThatLongComputationTask2WillTimeout() {
391 | givenThatLongComputationTaskWillTimeout(mockLongComputationTask2, mockLongComputationTask2Deferred)
392 | }
393 |
394 | private fun givenThatLongComputationTask3WillTimeout() {
395 | givenThatLongComputationTaskWillTimeout(mockLongComputationTask3, mockLongComputationTask3Deferred)
396 | }
397 |
398 | private fun givenThatChannelTaskWillReturn(channelTask: ChannelTaskUseCase,
399 | taskExecutionDeferred: Deferred,
400 | taskExecutionResult: TaskExecutionResult,
401 | hasBackpressureChannel: Boolean) = runBlocking {
402 | given(taskExecutionDeferred.await()).willReturn(taskExecutionResult)
403 | given(channelTask.executeAsync(
404 | anyObj(testAppCoroutineScope),
405 | anyLong(),
406 | anyLong(),
407 | anyObj(Channel()),
408 | if (hasBackpressureChannel) anyObj>(Channel()) else eq(null))).willReturn(taskExecutionDeferred)
409 | }
410 |
411 | private fun givenThatChannelTask1WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
412 | givenThatChannelTaskWillReturn(mockChannelTask1, mockChannelTask1Deferred, taskExecutionResult, false)
413 | }
414 |
415 | private fun givenThatChannelTask2WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
416 | givenThatChannelTaskWillReturn(mockChannelTask2, mockChannelTask2Deferred, taskExecutionResult, false)
417 | }
418 |
419 | private fun givenThatChannelTask3WillReturn(taskExecutionResult: TaskExecutionResult) = runBlocking {
420 | givenThatChannelTaskWillReturn(mockChannelTask3, mockChannelTask3Deferred, taskExecutionResult, true)
421 | }
422 |
423 | private fun givenThatChannel1WillSend(items: List) {
424 | givenChannel1Items = items
425 | }
426 |
427 | private fun givenThatChannel2WillSend(items: List) {
428 | givenChannel2Items = items
429 | }
430 |
431 | private fun givenThatChannel3WillSend(items: List) {
432 | givenChannel3Items = items
433 | }
434 |
435 | private fun givenThatBackpressureChannel3WillSend(items: List) {
436 | givenBackpressureChannel3Items = items
437 | }
438 |
439 | private fun givenThatExceptionsTaskExecuteWillThrow(exception: Class) = runBlocking {
440 | given(mockExceptionsTask.execute(anyLong(), anyLong(), anyLong())).willAnswer { throw exception.newInstance() }
441 | }
442 |
443 | private fun givenThatExceptionsTaskExecuteAsyncWillThrow(exception: Class) = runBlocking {
444 | given(mockExceptionsTask2Deferred.await()).willAnswer { throw exception.newInstance() }
445 | given(mockExceptionsTask.executeAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(mockExceptionsTask2Deferred)
446 | }
447 |
448 | private fun givenThatExceptionsTaskExecuteWithRepositoryAsyncWillThrow(exception: Class) = runBlocking {
449 | given(mockExceptionsTask3Deferred.await()).willAnswer { throw exception.newInstance() }
450 | given(mockExceptionsTask.executeWithRepositoryAsync(anyObj(testAppCoroutineScope), anyLong(), anyLong(), anyLong())).willReturn(mockExceptionsTask3Deferred)
451 | }
452 |
453 | // endregion Given
454 |
455 | // region When
456 |
457 | private fun whenRunSequentialTasks() {
458 | subject.runSequentialTasks()
459 | }
460 |
461 | private fun whenRunParallelTasks() {
462 | subject.runParallelTasks()
463 | }
464 |
465 | private fun whenRunSequentialTasksWithError() {
466 | subject.runSequentialTasksWithError()
467 | }
468 |
469 | private fun whenRunParallelTasksWithError() {
470 | subject.runParallelTasksWithError()
471 | }
472 |
473 | private fun whenRunMultipleTasks() {
474 | subject.runMultipleTasks()
475 | }
476 |
477 | private fun whenRunCallbackTasksWithError() {
478 | subject.runCallbackTasksWithError()
479 | }
480 |
481 | private fun whenRunLongComputationTasks() {
482 | subject.runLongComputationTasks()
483 | }
484 |
485 | private fun whenCancelLongComputationTask2() {
486 | subject.cancelLongComputationTask2()
487 | }
488 |
489 | private fun whenRunLongComputationTasksWithTimeout() {
490 | subject.runLongComputationTasksWithTimeout()
491 | }
492 |
493 | private fun whenRunChannelsTasks() = runBlocking {
494 | subject.runChannelsTasks()
495 |
496 | val mockSendChannel = mock(Channel::class.java) as SendChannel
497 | val channel1Captor = ArgumentCaptor.forClass(SendChannel::class.java)
498 | val channel2Captor = ArgumentCaptor.forClass(SendChannel::class.java)
499 | val channel3Captor = ArgumentCaptor.forClass(SendChannel::class.java)
500 | val backpressureChannel3Captor = ArgumentCaptor.forClass(SendChannel::class.java)
501 |
502 | then(mockChannelTask1).should().executeAsync(
503 | anyObj(testAppCoroutineScope),
504 | anyLong(),
505 | anyLong(),
506 | captureObj(channel1Captor, mockSendChannel) as SendChannel,
507 | eq(null))
508 | then(mockChannelTask2).should().executeAsync(
509 | anyObj(testAppCoroutineScope),
510 | anyLong(),
511 | anyLong(),
512 | captureObj(channel2Captor, mockSendChannel) as SendChannel,
513 | eq(null))
514 | then(mockChannelTask3).should().executeAsync(
515 | anyObj(testAppCoroutineScope),
516 | anyLong(),
517 | anyLong(),
518 | captureObj(channel3Captor, mockSendChannel) as SendChannel,
519 | captureObj(backpressureChannel3Captor, mockSendChannel) as SendChannel)
520 |
521 | val givenChannel1 = channel1Captor.value as Channel
522 | val givenChannel2 = channel2Captor.value as Channel
523 | val givenChannel3 = channel3Captor.value as Channel
524 | val givenBackpressureChannel3 = backpressureChannel3Captor.value as Channel
525 |
526 | givenChannel1Items.forEach { givenChannel1.send(it) }
527 | givenChannel2Items.forEach { givenChannel2.send(it) }
528 | givenChannel3Items.forEach { givenChannel3.send(it) }
529 | givenBackpressureChannel3Items.forEach { givenBackpressureChannel3.send(it) }
530 |
531 | givenChannel1.close()
532 | givenChannel2.close()
533 | givenChannel3.close()
534 | givenBackpressureChannel3.close()
535 | }
536 |
537 | private fun whenRunExceptionsTasks() {
538 | subject.runExceptionsTasks()
539 | }
540 |
541 | // endregion When
542 |
543 | // region Then
544 |
545 | private fun thenTaskStatesSequenceIs(taskNumber: Int, states: List) {
546 | val inOrder = inOrder(mockView)
547 | var lastState: TaskExecutionState? = null
548 | var times = 0
549 |
550 | for (state in states) {
551 | if (lastState != null && state != lastState) {
552 | then(mockView).should(inOrder, times(times)).updateTaskExecutionState(taskNumber, lastState)
553 | times = 0
554 | }
555 |
556 | lastState = state
557 | times++
558 | }
559 |
560 | if (lastState != null) {
561 | then(mockView).should(inOrder, times(times)).updateTaskExecutionState(taskNumber, lastState)
562 | }
563 | }
564 |
565 | private fun thenNoMoreInteractionsWithView() {
566 | then(mockView).shouldHaveNoMoreInteractions()
567 | }
568 |
569 | private fun thenWaitForCompletionOfLongComputationTasks() = runBlocking {
570 | then(mockLongComputationTask1Deferred).should().await()
571 | then(mockLongComputationTask2Deferred).should().await()
572 | then(mockLongComputationTask3Deferred).should().await()
573 | }
574 |
575 | private fun thenTaskIsCancelled(taskDeferred: Deferred) {
576 | then(taskDeferred).should().cancel()
577 | }
578 |
579 | private fun thenWaitForCompletionOfChannelsTasks() = runBlocking {
580 | then(mockChannelTask1Deferred).should().await()
581 | then(mockChannelTask2Deferred).should().await()
582 | then(mockChannelTask3Deferred).should().await()
583 | }
584 |
585 | // endregion Then
586 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/testing/BaseMockitoTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.testing
2 |
3 | import andreabresolin.androidcoroutinesplayground.app.coroutines.AppCoroutinesConfiguration
4 | import andreabresolin.androidcoroutinesplayground.app.coroutines.testing.TestAppCoroutineScope
5 | import kotlinx.coroutines.Dispatchers
6 | import org.junit.Before
7 | import org.junit.BeforeClass
8 | import org.junit.runner.RunWith
9 | import org.mockito.junit.MockitoJUnitRunner
10 |
11 | @RunWith(MockitoJUnitRunner::class)
12 | abstract class BaseMockitoTest {
13 |
14 | companion object {
15 | @BeforeClass
16 | @JvmStatic
17 | fun beforeClassBaseMockitoTest() {
18 | with (AppCoroutinesConfiguration) {
19 | uiDispatcher = Dispatchers.Unconfined
20 | backgroundDispatcher = Dispatchers.Unconfined
21 | ioDispatcher = Dispatchers.Unconfined
22 | isDelayEnabled = false
23 | useTestTimeout = true
24 | }
25 | }
26 | }
27 |
28 | protected lateinit var testAppCoroutineScope: TestAppCoroutineScope
29 |
30 | @Before
31 | fun beforeBaseMockitoTest() {
32 | testAppCoroutineScope = TestAppCoroutineScope()
33 | }
34 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/testing/BasePresenterTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.testing
2 |
3 | abstract class BasePresenterTest : BaseMockitoTest()
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/testing/BaseViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.testing
2 |
3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
4 | import androidx.lifecycle.Lifecycle
5 | import androidx.lifecycle.LifecycleOwner
6 | import androidx.lifecycle.LifecycleRegistry
7 | import androidx.lifecycle.LiveData
8 | import org.assertj.core.api.Assertions.assertThat
9 | import org.junit.After
10 | import org.junit.Before
11 | import org.junit.Rule
12 | import org.junit.rules.TestRule
13 | import org.mockito.Mockito.mock
14 |
15 | abstract class BaseViewModelTest : BaseMockitoTest() {
16 |
17 | @get:Rule
18 | internal var rule: TestRule = InstantTaskExecutorRule()
19 |
20 | private lateinit var testLifecycle: Lifecycle
21 | private lateinit var liveDataChanges: MutableMap, MutableList<*>>
22 |
23 | @Before
24 | fun beforeViewModelTest() {
25 | val lifecycleRegistry = LifecycleRegistry(mock(LifecycleOwner::class.java))
26 | lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
27 | testLifecycle = lifecycleRegistry
28 |
29 | liveDataChanges = mutableMapOf()
30 | }
31 |
32 | @After
33 | fun afterViewModelTest() {
34 | liveDataChanges.forEach { liveData, _ ->
35 | liveData.removeObservers { testLifecycle }
36 | }
37 | }
38 |
39 | @Suppress("UNCHECKED_CAST")
40 | protected fun trackLiveDataChanges(liveData: LiveData) {
41 | liveData.observe({ testLifecycle }, { newState ->
42 | var statesSequence: MutableList? = liveDataChanges[liveData] as MutableList?
43 |
44 | if (statesSequence == null) {
45 | statesSequence = mutableListOf()
46 | liveDataChanges[liveData] = statesSequence
47 | }
48 |
49 | statesSequence.add(newState)
50 | })
51 | }
52 |
53 | @Suppress("UNCHECKED_CAST")
54 | protected fun assertThatLiveDataStatesSequenceIs(liveData: LiveData, expectedStatesSequence: List) {
55 | assertThat(liveDataChanges[liveData] as List?).isEqualTo(expectedStatesSequence)
56 | }
57 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/testing/KotlinTestUtils.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.testing
2 |
3 | import org.mockito.ArgumentCaptor
4 | import org.mockito.ArgumentMatchers.any
5 | import org.mockito.ArgumentMatchers.eq
6 |
7 | interface KotlinTestUtils {
8 |
9 | companion object {
10 | fun eqObj(obj: T): T {
11 | eq(obj)
12 | return obj
13 | }
14 |
15 | inline fun anyObj(obj: T): T {
16 | any(T::class.java)
17 | return obj
18 | }
19 |
20 | fun captureObj(captor: ArgumentCaptor, obj: T): T {
21 | captor.capture()
22 | return obj
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/test/java/andreabresolin/androidcoroutinesplayground/testing/MockableDeferred.kt:
--------------------------------------------------------------------------------
1 | package andreabresolin.androidcoroutinesplayground.testing
2 |
3 | import kotlinx.coroutines.Deferred
4 |
5 | abstract class MockableDeferred : Deferred {
6 |
7 | override fun cancel() {
8 | // Do nothing
9 | }
10 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.31'
5 | repositories {
6 | google()
7 | jcenter()
8 |
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.4.0'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | google()
21 | jcenter()
22 |
23 | }
24 | }
25 |
26 | task clean(type: Delete) {
27 | delete rootProject.buildDir
28 | }
29 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreabresolin/AndroidCoroutinesPlayground/a673b8740ad12de7d898c845944facdbe4fb0daf/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Apr 21 20:38:47 BST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------