├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── resources
├── ajax-loader.gif
└── logback.xml
├── settings.gradle
├── src
├── contributors
│ ├── Contributors.kt
│ ├── ContributorsUI.kt
│ ├── GitHubService.kt
│ ├── Logger.kt
│ ├── Params.kt
│ └── main.kt
├── samples
│ ├── ChannelsSample.kt
│ ├── ConcurrencySample.kt
│ └── SamplesLogger.kt
└── tasks
│ ├── Aggregation.kt
│ ├── Request1Blocking.kt
│ ├── Request2Background.kt
│ ├── Request3Callbacks.kt
│ ├── Request4Suspend.kt
│ ├── Request5Concurrent.kt
│ ├── Request5NotCancellable.kt
│ ├── Request6Progress.kt
│ └── Request7Channels.kt
└── test
├── contributors
├── MockGithubService.kt
└── testData.kt
├── samples
└── SampleTest.kt
└── tasks
├── AggregationKtTest.kt
├── Request1BlockingKtTest.kt
├── Request3CallbacksKtTest.kt
├── Request4SuspendKtTest.kt
├── Request5ConcurrentKtTest.kt
├── Request6ProgressKtTest.kt
└── Request7ChannelsKtTest.kt
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | .idea
3 | out
4 | build
5 | *.iml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)
2 | [](https://www.apache.org/licenses/LICENSE-2.0)
3 |
4 | # Introduction to Coroutines and Channels Hands-On Lab
5 |
6 | This repository is the code corresponding to the
7 | [Introduction to Coroutines and Channels](https://play.kotlinlang.org/hands-on/Introduction%20to%20Coroutines%20and%20Channels/01_Introduction)
8 | Hands-On Lab.
9 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.jetbrains.kotlin.jvm' version '1.7.21'
3 | id 'org.jetbrains.kotlin.plugin.serialization' version '1.7.21'
4 | }
5 |
6 | group 'intro-coroutines'
7 | version '1.0-SNAPSHOT'
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | implementation "org.jetbrains.kotlin:kotlin-stdlib"
15 | implementation "org.jetbrains.kotlin:kotlin-reflect"
16 | implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.1")
17 |
18 | def coroutines_version = '1.6.4'
19 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
20 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-swing:$coroutines_version"
21 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutines_version"
22 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-slf4j:$coroutines_version"
23 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-debug:$coroutines_version"
24 |
25 | implementation 'ch.qos.logback:logback-classic:1.4.5'
26 |
27 | def retrofit_version = '2.9.0'
28 | implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
29 | implementation "com.squareup.retrofit2:retrofit-mock:$retrofit_version"
30 | implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0"
31 | implementation 'com.squareup.okhttp3:okhttp:4.10.0'
32 |
33 | implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
34 | implementation 'io.reactivex.rxjava2:rxkotlin:2.4.0'
35 | implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
36 |
37 | testImplementation 'junit:junit:4.13.2'
38 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version"
39 | }
40 |
41 | compileKotlin {
42 | kotlinOptions {
43 | jvmTarget = "1.8"
44 | freeCompilerArgs += "-opt-in=kotlin.RequiresOptIn"
45 | }
46 | }
47 |
48 | compileTestKotlin {
49 | kotlinOptions {
50 | jvmTarget = "1.8"
51 | freeCompilerArgs += "-opt-in=kotlin.RequiresOptIn"
52 | }
53 | }
54 |
55 | sourceSets {
56 | main.kotlin.srcDirs = ['src']
57 | main.resources.srcDirs = ['resources']
58 | test.kotlin.srcDirs = ['test']
59 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kotlin-hands-on/intro-coroutines/eee89091c695b3b35993cf6611503ed04a65bcae/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 30 12:29:46 CEST 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-7.6-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 |
--------------------------------------------------------------------------------
/resources/ajax-loader.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kotlin-hands-on/intro-coroutines/eee89091c695b3b35993cf6611503ed04a65bcae/resources/ajax-loader.gif
--------------------------------------------------------------------------------
/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %r [%thread] %-5level %logger{36} - %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'intro-coroutines'
2 |
3 |
--------------------------------------------------------------------------------
/src/contributors/Contributors.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import contributors.Contributors.LoadingStatus.*
4 | import contributors.Variant.*
5 | import kotlinx.coroutines.*
6 | import tasks.*
7 | import java.awt.event.ActionListener
8 | import javax.swing.SwingUtilities
9 | import kotlin.coroutines.CoroutineContext
10 | import kotlin.system.exitProcess
11 |
12 | enum class Variant {
13 | BLOCKING, // Request1Blocking
14 | BACKGROUND, // Request2Background
15 | CALLBACKS, // Request3Callbacks
16 | SUSPEND, // Request4Coroutine
17 | CONCURRENT, // Request5Concurrent
18 | NOT_CANCELLABLE, // Request6NotCancellable
19 | PROGRESS, // Request6Progress
20 | CHANNELS // Request7Channels
21 | }
22 |
23 | interface Contributors: CoroutineScope {
24 |
25 | val job: Job
26 |
27 | override val coroutineContext: CoroutineContext
28 | get() = job + Dispatchers.Main
29 |
30 | fun init() {
31 | // Start a new loading on 'load' click
32 | addLoadListener {
33 | saveParams()
34 | loadContributors()
35 | }
36 |
37 | // Save preferences and exit on closing the window
38 | addOnWindowClosingListener {
39 | job.cancel()
40 | saveParams()
41 | exitProcess(0)
42 | }
43 |
44 | // Load stored params (user & password values)
45 | loadInitialParams()
46 | }
47 |
48 | fun loadContributors() {
49 | val (username, password, org, _) = getParams()
50 | val req = RequestData(username, password, org)
51 |
52 | clearResults()
53 | val service = createGitHubService(req.username, req.password)
54 |
55 | val startTime = System.currentTimeMillis()
56 | when (getSelectedVariant()) {
57 | BLOCKING -> { // Blocking UI thread
58 | val users = loadContributorsBlocking(service, req)
59 | updateResults(users, startTime)
60 | }
61 | BACKGROUND -> { // Blocking a background thread
62 | loadContributorsBackground(service, req) { users ->
63 | SwingUtilities.invokeLater {
64 | updateResults(users, startTime)
65 | }
66 | }
67 | }
68 | CALLBACKS -> { // Using callbacks
69 | loadContributorsCallbacks(service, req) { users ->
70 | SwingUtilities.invokeLater {
71 | updateResults(users, startTime)
72 | }
73 | }
74 | }
75 | SUSPEND -> { // Using coroutines
76 | launch {
77 | val users = loadContributorsSuspend(service, req)
78 | updateResults(users, startTime)
79 | }.setUpCancellation()
80 | }
81 | CONCURRENT -> { // Performing requests concurrently
82 | launch {
83 | val users = loadContributorsConcurrent(service, req)
84 | updateResults(users, startTime)
85 | }.setUpCancellation()
86 | }
87 | NOT_CANCELLABLE -> { // Performing requests in a non-cancellable way
88 | launch {
89 | val users = loadContributorsNotCancellable(service, req)
90 | updateResults(users, startTime)
91 | }.setUpCancellation()
92 | }
93 | PROGRESS -> { // Showing progress
94 | launch(Dispatchers.Default) {
95 | loadContributorsProgress(service, req) { users, completed ->
96 | withContext(Dispatchers.Main) {
97 | updateResults(users, startTime, completed)
98 | }
99 | }
100 | }.setUpCancellation()
101 | }
102 | CHANNELS -> { // Performing requests concurrently and showing progress
103 | launch(Dispatchers.Default) {
104 | loadContributorsChannels(service, req) { users, completed ->
105 | withContext(Dispatchers.Main) {
106 | updateResults(users, startTime, completed)
107 | }
108 | }
109 | }.setUpCancellation()
110 | }
111 | }
112 | }
113 |
114 | private enum class LoadingStatus { COMPLETED, CANCELED, IN_PROGRESS }
115 |
116 | private fun clearResults() {
117 | updateContributors(listOf())
118 | updateLoadingStatus(IN_PROGRESS)
119 | setActionsStatus(newLoadingEnabled = false)
120 | }
121 |
122 | private fun updateResults(
123 | users: List,
124 | startTime: Long,
125 | completed: Boolean = true
126 | ) {
127 | updateContributors(users)
128 | updateLoadingStatus(if (completed) COMPLETED else IN_PROGRESS, startTime)
129 | if (completed) {
130 | setActionsStatus(newLoadingEnabled = true)
131 | }
132 | }
133 |
134 | private fun updateLoadingStatus(
135 | status: LoadingStatus,
136 | startTime: Long? = null
137 | ) {
138 | val time = if (startTime != null) {
139 | val time = System.currentTimeMillis() - startTime
140 | "${(time / 1000)}.${time % 1000 / 100} sec"
141 | } else ""
142 |
143 | val text = "Loading status: " +
144 | when (status) {
145 | COMPLETED -> "completed in $time"
146 | IN_PROGRESS -> "in progress $time"
147 | CANCELED -> "canceled"
148 | }
149 | setLoadingStatus(text, status == IN_PROGRESS)
150 | }
151 |
152 | private fun Job.setUpCancellation() {
153 | // make active the 'cancel' button
154 | setActionsStatus(newLoadingEnabled = false, cancellationEnabled = true)
155 |
156 | val loadingJob = this
157 |
158 | // cancel the loading job if the 'cancel' button was clicked
159 | val listener = ActionListener {
160 | loadingJob.cancel()
161 | updateLoadingStatus(CANCELED)
162 | }
163 | addCancelListener(listener)
164 |
165 | // update the status and remove the listener after the loading job is completed
166 | launch {
167 | loadingJob.join()
168 | setActionsStatus(newLoadingEnabled = true)
169 | removeCancelListener(listener)
170 | }
171 | }
172 |
173 | fun loadInitialParams() {
174 | setParams(loadStoredParams())
175 | }
176 |
177 | fun saveParams() {
178 | val params = getParams()
179 | if (params.username.isEmpty() && params.password.isEmpty()) {
180 | removeStoredParams()
181 | }
182 | else {
183 | saveParams(params)
184 | }
185 | }
186 |
187 | fun getSelectedVariant(): Variant
188 |
189 | fun updateContributors(users: List)
190 |
191 | fun setLoadingStatus(text: String, iconRunning: Boolean)
192 |
193 | fun setActionsStatus(newLoadingEnabled: Boolean, cancellationEnabled: Boolean = false)
194 |
195 | fun addCancelListener(listener: ActionListener)
196 |
197 | fun removeCancelListener(listener: ActionListener)
198 |
199 | fun addLoadListener(listener: () -> Unit)
200 |
201 | fun addOnWindowClosingListener(listener: () -> Unit)
202 |
203 | fun setParams(params: Params)
204 |
205 | fun getParams(): Params
206 | }
207 |
--------------------------------------------------------------------------------
/src/contributors/ContributorsUI.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import kotlinx.coroutines.Job
4 | import java.awt.Dimension
5 | import java.awt.GridBagConstraints
6 | import java.awt.GridBagLayout
7 | import java.awt.Insets
8 | import java.awt.event.ActionListener
9 | import java.awt.event.WindowAdapter
10 | import java.awt.event.WindowEvent
11 | import javax.swing.*
12 | import javax.swing.table.DefaultTableModel
13 |
14 | private val INSETS = Insets(3, 10, 3, 10)
15 | private val COLUMNS = arrayOf("Login", "Contributions")
16 |
17 | @Suppress("CONFLICTING_INHERITED_JVM_DECLARATIONS")
18 | class ContributorsUI : JFrame("GitHub Contributors"), Contributors {
19 | private val username = JTextField(20)
20 | private val password = JPasswordField(20)
21 | private val org = JTextField(20)
22 | private val variant = JComboBox(Variant.values())
23 | private val load = JButton("Load contributors")
24 | private val cancel = JButton("Cancel").apply { isEnabled = false }
25 |
26 | private val resultsModel = DefaultTableModel(COLUMNS, 0)
27 | private val results = JTable(resultsModel)
28 | private val resultsScroll = JScrollPane(results).apply {
29 | preferredSize = Dimension(200, 200)
30 | }
31 |
32 | private val loadingIcon = ImageIcon(javaClass.classLoader.getResource("ajax-loader.gif"))
33 | private val loadingStatus = JLabel("Start new loading", loadingIcon, SwingConstants.CENTER)
34 |
35 | override val job = Job()
36 |
37 | init {
38 | // Create UI
39 | rootPane.contentPane = JPanel(GridBagLayout()).apply {
40 | addLabeled("GitHub Username", username)
41 | addLabeled("Password/Token", password)
42 | addWideSeparator()
43 | addLabeled("Organization", org)
44 | addLabeled("Variant", variant)
45 | addWideSeparator()
46 | addWide(JPanel().apply {
47 | add(load)
48 | add(cancel)
49 | })
50 | addWide(resultsScroll) {
51 | weightx = 1.0
52 | weighty = 1.0
53 | fill = GridBagConstraints.BOTH
54 | }
55 | addWide(loadingStatus)
56 | }
57 | // Initialize actions
58 | init()
59 | }
60 |
61 | override fun getSelectedVariant(): Variant = variant.getItemAt(variant.selectedIndex)
62 |
63 | override fun updateContributors(users: List) {
64 | if (users.isNotEmpty()) {
65 | log.info("Updating result with ${users.size} rows")
66 | }
67 | else {
68 | log.info("Clearing result")
69 | }
70 | resultsModel.setDataVector(users.map {
71 | arrayOf(it.login, it.contributions)
72 | }.toTypedArray(), COLUMNS)
73 | }
74 |
75 | override fun setLoadingStatus(text: String, iconRunning: Boolean) {
76 | loadingStatus.text = text
77 | loadingStatus.icon = if (iconRunning) loadingIcon else null
78 | }
79 |
80 | override fun addCancelListener(listener: ActionListener) {
81 | cancel.addActionListener(listener)
82 | }
83 |
84 | override fun removeCancelListener(listener: ActionListener) {
85 | cancel.removeActionListener(listener)
86 | }
87 |
88 | override fun addLoadListener(listener: () -> Unit) {
89 | load.addActionListener { listener() }
90 | }
91 |
92 | override fun addOnWindowClosingListener(listener: () -> Unit) {
93 | addWindowListener(object : WindowAdapter() {
94 | override fun windowClosing(e: WindowEvent?) {
95 | listener()
96 | }
97 | })
98 | }
99 |
100 | override fun setActionsStatus(newLoadingEnabled: Boolean, cancellationEnabled: Boolean) {
101 | load.isEnabled = newLoadingEnabled
102 | cancel.isEnabled = cancellationEnabled
103 | }
104 |
105 | override fun setParams(params: Params) {
106 | username.text = params.username
107 | password.text = params.password
108 | org.text = params.org
109 | variant.selectedIndex = params.variant.ordinal
110 | }
111 |
112 | override fun getParams(): Params {
113 | return Params(username.text, password.password.joinToString(""), org.text, getSelectedVariant())
114 | }
115 | }
116 |
117 | fun JPanel.addLabeled(label: String, component: JComponent) {
118 | add(JLabel(label), GridBagConstraints().apply {
119 | gridx = 0
120 | insets = INSETS
121 | })
122 | add(component, GridBagConstraints().apply {
123 | gridx = 1
124 | insets = INSETS
125 | anchor = GridBagConstraints.WEST
126 | fill = GridBagConstraints.HORIZONTAL
127 | weightx = 1.0
128 | })
129 | }
130 |
131 | fun JPanel.addWide(component: JComponent, constraints: GridBagConstraints.() -> Unit = {}) {
132 | add(component, GridBagConstraints().apply {
133 | gridx = 0
134 | gridwidth = 2
135 | insets = INSETS
136 | constraints()
137 | })
138 | }
139 |
140 | fun JPanel.addWideSeparator() {
141 | addWide(JSeparator()) {
142 | fill = GridBagConstraints.HORIZONTAL
143 | }
144 | }
145 |
146 | fun setDefaultFontSize(size: Float) {
147 | for (key in UIManager.getLookAndFeelDefaults().keys.toTypedArray()) {
148 | if (key.toString().lowercase().contains("font")) {
149 | val font = UIManager.getDefaults().getFont(key) ?: continue
150 | val newFont = font.deriveFont(size)
151 | UIManager.put(key, newFont)
152 | }
153 | }
154 | }
--------------------------------------------------------------------------------
/src/contributors/GitHubService.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
4 | import kotlinx.serialization.ExperimentalSerializationApi
5 | import kotlinx.serialization.Serializable
6 | import kotlinx.serialization.json.Json
7 | import okhttp3.MediaType.Companion.toMediaType
8 | import okhttp3.OkHttpClient
9 | import retrofit2.Call
10 | import retrofit2.Response
11 | import retrofit2.Retrofit
12 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
13 | import retrofit2.http.GET
14 | import retrofit2.http.Path
15 | import java.util.Base64
16 |
17 | interface GitHubService {
18 | @GET("orgs/{org}/repos?per_page=100")
19 | fun getOrgReposCall(
20 | @Path("org") org: String
21 | ): Call>
22 |
23 | @GET("repos/{owner}/{repo}/contributors?per_page=100")
24 | fun getRepoContributorsCall(
25 | @Path("owner") owner: String,
26 | @Path("repo") repo: String
27 | ): Call>
28 | }
29 |
30 | @Serializable
31 | data class Repo(
32 | val id: Long,
33 | val name: String
34 | )
35 |
36 | @Serializable
37 | data class User(
38 | val login: String,
39 | val contributions: Int
40 | )
41 |
42 | @Serializable
43 | data class RequestData(
44 | val username: String,
45 | val password: String,
46 | val org: String
47 | )
48 |
49 | @OptIn(ExperimentalSerializationApi::class)
50 | fun createGitHubService(username: String, password: String): GitHubService {
51 | val authToken = "Basic " + Base64.getEncoder().encode("$username:$password".toByteArray()).toString(Charsets.UTF_8)
52 | val httpClient = OkHttpClient.Builder()
53 | .addInterceptor { chain ->
54 | val original = chain.request()
55 | val builder = original.newBuilder()
56 | .header("Accept", "application/vnd.github.v3+json")
57 | .header("Authorization", authToken)
58 | val request = builder.build()
59 | chain.proceed(request)
60 | }
61 | .build()
62 |
63 | val contentType = "application/json".toMediaType()
64 | val retrofit = Retrofit.Builder()
65 | .baseUrl("https://api.github.com")
66 | .addConverterFactory(Json { ignoreUnknownKeys = true }.asConverterFactory(contentType))
67 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
68 | .client(httpClient)
69 | .build()
70 | return retrofit.create(GitHubService::class.java)
71 | }
72 |
--------------------------------------------------------------------------------
/src/contributors/Logger.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import org.slf4j.Logger
4 | import org.slf4j.LoggerFactory
5 | import retrofit2.Response
6 |
7 | val log: Logger = LoggerFactory.getLogger("Contributors")
8 |
9 | fun log(msg: String?) {
10 | log.info(msg)
11 | }
12 |
13 | fun logRepos(req: RequestData, response: Response>) {
14 | val repos = response.body()
15 | if (!response.isSuccessful || repos == null) {
16 | log.error("Failed loading repos for ${req.org} with response: '${response.code()}: ${response.message()}'")
17 | }
18 | else {
19 | log.info("${req.org}: loaded ${repos.size} repos")
20 | }
21 | }
22 |
23 | fun logUsers(repo: Repo, response: Response>) {
24 | val users = response.body()
25 | if (!response.isSuccessful || users == null) {
26 | log.error("Failed loading contributors for ${repo.name} with response '${response.code()}: ${response.message()}'")
27 | }
28 | else {
29 | log.info("${repo.name}: loaded ${users.size} contributors")
30 | }
31 | }
--------------------------------------------------------------------------------
/src/contributors/Params.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import java.util.prefs.Preferences
4 |
5 | private fun prefNode(): Preferences = Preferences.userRoot().node("ContributorsUI")
6 |
7 | data class Params(val username: String, val password: String, val org: String, val variant: Variant)
8 |
9 | fun loadStoredParams(): Params {
10 | return prefNode().run {
11 | Params(
12 | get("username", ""),
13 | get("password", ""),
14 | get("org", "kotlin"),
15 | Variant.valueOf(get("variant", Variant.BLOCKING.name))
16 | )
17 | }
18 | }
19 |
20 | fun removeStoredParams() {
21 | prefNode().removeNode()
22 | }
23 |
24 | fun saveParams(params: Params) {
25 | prefNode().apply {
26 | put("username", params.username)
27 | put("password", params.password)
28 | put("org", params.org)
29 | put("variant", params.variant.name)
30 | sync()
31 | }
32 | }
--------------------------------------------------------------------------------
/src/contributors/main.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | fun main() {
4 | setDefaultFontSize(18f)
5 | ContributorsUI().apply {
6 | pack()
7 | setLocationRelativeTo(null)
8 | isVisible = true
9 | }
10 | }
--------------------------------------------------------------------------------
/src/samples/ChannelsSample.kt:
--------------------------------------------------------------------------------
1 | package samples
2 |
3 | import kotlinx.coroutines.channels.Channel
4 | import kotlinx.coroutines.*
5 |
6 | fun main() = runBlocking {
7 | val channel = Channel()
8 | launch {
9 | channel.send("A1")
10 | channel.send("A2")
11 | log("A done")
12 | }
13 | launch {
14 | channel.send("B1")
15 | log("B done")
16 | }
17 | launch {
18 | repeat(3) {
19 | val x = channel.receive()
20 | log(x)
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/samples/ConcurrencySample.kt:
--------------------------------------------------------------------------------
1 | package samples
2 |
3 | import kotlinx.coroutines.*
4 |
5 | fun main() = runBlocking {
6 | val deferred: Deferred = async(Dispatchers.Default) {
7 | loadData()
8 | }
9 | log("waiting...")
10 | log(deferred.await())
11 | }
12 |
13 | suspend fun loadData(): Int {
14 | log("loading...")
15 | delay(1000L)
16 | log("loaded!")
17 | return 42
18 | }
--------------------------------------------------------------------------------
/src/samples/SamplesLogger.kt:
--------------------------------------------------------------------------------
1 | package samples
2 |
3 | import org.slf4j.Logger
4 | import org.slf4j.LoggerFactory
5 |
6 | val log: Logger = LoggerFactory.getLogger("Samples")
7 |
8 | fun log(msg: Any?) {
9 | log.info(msg.toString())
10 | }
11 |
--------------------------------------------------------------------------------
/src/tasks/Aggregation.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.User
4 |
5 | /*
6 | TODO: Write aggregation code.
7 |
8 | In the initial list each user is present several times, once for each
9 | repository he or she contributed to.
10 | Merge duplications: each user should be present only once in the resulting list
11 | with the total value of contributions for all the repositories.
12 | Users should be sorted in a descending order by their contributions.
13 |
14 | The corresponding test can be found in test/tasks/AggregationKtTest.kt.
15 | You can use 'Navigate | Test' menu action (note the shortcut) to navigate to the test.
16 | */
17 | fun List.aggregate(): List =
18 | this
--------------------------------------------------------------------------------
/src/tasks/Request1Blocking.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 | import retrofit2.Response
5 |
6 | fun loadContributorsBlocking(service: GitHubService, req: RequestData) : List {
7 | val repos = service
8 | .getOrgReposCall(req.org)
9 | .execute() // Executes request and blocks the current thread
10 | .also { logRepos(req, it) }
11 | .body() ?: emptyList()
12 |
13 | return repos.flatMap { repo ->
14 | service
15 | .getRepoContributorsCall(req.org, repo.name)
16 | .execute() // Executes request and blocks the current thread
17 | .also { logUsers(repo, it) }
18 | .bodyList()
19 | }.aggregate()
20 | }
21 |
22 | fun Response>.bodyList(): List {
23 | return body() ?: emptyList()
24 | }
--------------------------------------------------------------------------------
/src/tasks/Request2Background.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.GitHubService
4 | import contributors.RequestData
5 | import contributors.User
6 | import kotlin.concurrent.thread
7 |
8 | fun loadContributorsBackground(service: GitHubService, req: RequestData, updateResults: (List) -> Unit) {
9 | thread {
10 | loadContributorsBlocking(service, req)
11 | }
12 | }
--------------------------------------------------------------------------------
/src/tasks/Request3Callbacks.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 | import retrofit2.Call
5 | import retrofit2.Callback
6 | import retrofit2.Response
7 | import java.util.*
8 | import java.util.concurrent.atomic.AtomicInteger
9 |
10 | fun loadContributorsCallbacks(service: GitHubService, req: RequestData, updateResults: (List) -> Unit) {
11 | service.getOrgReposCall(req.org).onResponse { responseRepos ->
12 | logRepos(req, responseRepos)
13 | val repos = responseRepos.bodyList()
14 | val allUsers = mutableListOf()
15 | for (repo in repos) {
16 | service.getRepoContributorsCall(req.org, repo.name).onResponse { responseUsers ->
17 | logUsers(repo, responseUsers)
18 | val users = responseUsers.bodyList()
19 | allUsers += users
20 | }
21 | }
22 | // TODO: Why this code doesn't work? How to fix that?
23 | updateResults(allUsers.aggregate())
24 | }
25 | }
26 |
27 | inline fun Call.onResponse(crossinline callback: (Response) -> Unit) {
28 | enqueue(object : Callback {
29 | override fun onResponse(call: Call, response: Response) {
30 | callback(response)
31 | }
32 |
33 | override fun onFailure(call: Call, t: Throwable) {
34 | log.error("Call failed", t)
35 | }
36 | })
37 | }
38 |
--------------------------------------------------------------------------------
/src/tasks/Request4Suspend.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 |
5 | suspend fun loadContributorsSuspend(service: GitHubService, req: RequestData): List {
6 | TODO()
7 | }
--------------------------------------------------------------------------------
/src/tasks/Request5Concurrent.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 | import kotlinx.coroutines.*
5 |
6 | suspend fun loadContributorsConcurrent(service: GitHubService, req: RequestData): List = coroutineScope {
7 | TODO()
8 | }
--------------------------------------------------------------------------------
/src/tasks/Request5NotCancellable.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 | import kotlinx.coroutines.*
5 | import kotlin.coroutines.coroutineContext
6 |
7 | suspend fun loadContributorsNotCancellable(service: GitHubService, req: RequestData): List {
8 | TODO()
9 | }
--------------------------------------------------------------------------------
/src/tasks/Request6Progress.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 |
5 | suspend fun loadContributorsProgress(
6 | service: GitHubService,
7 | req: RequestData,
8 | updateResults: suspend (List, completed: Boolean) -> Unit
9 | ) {
10 | TODO()
11 | }
12 |
--------------------------------------------------------------------------------
/src/tasks/Request7Channels.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.*
4 | import kotlinx.coroutines.channels.Channel
5 | import kotlinx.coroutines.coroutineScope
6 | import kotlinx.coroutines.launch
7 |
8 | suspend fun loadContributorsChannels(
9 | service: GitHubService,
10 | req: RequestData,
11 | updateResults: suspend (List, completed: Boolean) -> Unit
12 | ) {
13 | coroutineScope {
14 | TODO()
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/test/contributors/MockGithubService.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | import kotlinx.coroutines.delay
4 | import retrofit2.Call
5 | import retrofit2.Response
6 | import retrofit2.mock.Calls
7 |
8 | object MockGithubService : GitHubService {
9 | override fun getOrgReposCall(org: String): Call> {
10 | return Calls.response(repos)
11 | }
12 |
13 | override fun getRepoContributorsCall(owner: String, repo: String): Call> {
14 | return Calls.response(reposMap.getValue(repo).users)
15 | }
16 |
17 | /*
18 | // Uncomment the following implementations after adding these methods to GitHubService:
19 |
20 | override suspend fun getOrgRepos(org: String): Response> {
21 | delay(reposDelay)
22 | return Response.success(repos)
23 | }
24 |
25 | override suspend fun getRepoContributors(owner: String, repo: String): Response> {
26 | val testRepo = reposMap.getValue(repo)
27 | delay(testRepo.delay)
28 | return Response.success(testRepo.users)
29 | }
30 | */
31 | }
--------------------------------------------------------------------------------
/test/contributors/testData.kt:
--------------------------------------------------------------------------------
1 | package contributors
2 |
3 | val testRequestData = RequestData("username", "password", "org")
4 |
5 | data class TestRepo(val name: String, val delay: Long, val users: List)
6 |
7 | data class TestResults(val timeFromStart: Long, val users: List)
8 |
9 | const val reposDelay = 1000L
10 |
11 | val testRepos = listOf(
12 | TestRepo(
13 | "repo-1", 1000, listOf(
14 | User("user-1", 10),
15 | User("user-2", 20)
16 | )
17 | ),
18 | TestRepo(
19 | "repo-2", 1200, listOf(
20 | User("user-2", 30),
21 | User("user-1", 40)
22 | )
23 | ),
24 | TestRepo(
25 | "repo-3", 800, listOf(
26 | User("user-2", 50),
27 | User("user-3", 60)
28 | )
29 | )
30 | )
31 |
32 |
33 | val repos = testRepos.mapIndexed { index, testRepo -> Repo(index.toLong(), testRepo.name) }
34 |
35 | val reposMap = testRepos.associateBy { it.name }
36 |
37 | val expectedResults = TestResults(
38 | 4000, // 1000 + (1000 + 1200 + 800)
39 | listOf(
40 | User("user-2", 100),
41 | User("user-3", 60),
42 | User("user-1", 50)
43 | )
44 | )
45 |
46 | val expectedConcurrentResults = TestResults(
47 | 2200, // 1000 + max(1000, 1200, 800)
48 | expectedResults.users
49 | )
50 |
51 | val progressResults = listOf(
52 | TestResults(
53 | 2000, // 1000 + 1000
54 | listOf(User(login = "user-2", contributions = 20), User(login = "user-1", contributions = 10))
55 | ),
56 | TestResults(
57 | 3200, // 2000 + 1200
58 | listOf(User(login = "user-2", contributions = 50), User(login = "user-1", contributions = 50))
59 | ),
60 | expectedResults
61 | )
62 |
63 | val concurrentProgressResults = listOf(
64 | TestResults(
65 | 1800, // 1000 + 800
66 | listOf(User(login = "user-3", contributions = 60), User(login = "user-2", contributions = 50))
67 | ),
68 | TestResults(
69 | 2000, // 1000 + max(800, 1000)
70 | listOf(User(login = "user-2", contributions = 70), User(login = "user-3", contributions = 60),
71 | User(login = "user-1", contributions = 10))
72 | ),
73 | expectedConcurrentResults
74 | )
--------------------------------------------------------------------------------
/test/samples/SampleTest.kt:
--------------------------------------------------------------------------------
1 | package samples
2 |
3 | import kotlinx.coroutines.ExperimentalCoroutinesApi
4 | import kotlinx.coroutines.coroutineScope
5 | import kotlinx.coroutines.delay
6 | import kotlinx.coroutines.launch
7 | import kotlinx.coroutines.test.currentTime
8 | import kotlinx.coroutines.test.runTest
9 | import org.junit.Test
10 |
11 | @OptIn(ExperimentalCoroutinesApi::class)
12 | class SampleTest {
13 | @Test
14 | fun testDelayInSuspend() = runTest {
15 | val realStartTime = System.currentTimeMillis()
16 | val virtualStartTime = currentTime
17 |
18 | foo()
19 |
20 | println("${System.currentTimeMillis() - realStartTime} ms") // ~ 6 ms
21 | println("${currentTime - virtualStartTime} ms") // 1000 ms
22 | }
23 |
24 | suspend fun foo() {
25 | delay(1000) // auto-advances without delay
26 | println("foo") // executes eagerly when foo() is called
27 | }
28 |
29 | @Test
30 | fun testDelayInLaunch() = runTest {
31 | val realStartTime = System.currentTimeMillis()
32 | val virtualStartTime = currentTime
33 |
34 | bar()
35 |
36 | println("${System.currentTimeMillis() - realStartTime} ms") // ~ 11 ms
37 | println("${currentTime - virtualStartTime} ms") // 1000 ms
38 | }
39 |
40 | suspend fun bar() = coroutineScope {
41 | launch {
42 | delay(1000) // auto-advances without delay
43 | println("bar") // executes eagerly when bar() is called
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/test/tasks/AggregationKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.User
4 | import org.junit.Assert
5 | import org.junit.Test
6 |
7 | class AggregationKtTest {
8 | @Test
9 | fun testAggregation() {
10 | val actual = listOf(
11 | User("Alice", 1), User("Bob", 3),
12 | User("Alice", 2), User("Bob", 7),
13 | User("Charlie", 3), User("Alice", 5)
14 | ).aggregate()
15 | val expected = listOf(
16 | User("Bob", 10),
17 | User("Alice", 8),
18 | User("Charlie", 3)
19 | )
20 | Assert.assertEquals("Wrong result for 'aggregation'", expected, actual)
21 | }
22 | }
--------------------------------------------------------------------------------
/test/tasks/Request1BlockingKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.expectedResults
5 | import contributors.testRequestData
6 | import org.junit.Assert
7 | import org.junit.Test
8 |
9 | class Request1BlockingKtTest {
10 | @Test
11 | fun testAggregation() {
12 | val users = loadContributorsBlocking(MockGithubService, testRequestData)
13 | Assert.assertEquals("List of contributors should be sorted " +
14 | "by the number of contributions in a descending order",
15 | expectedResults.users, users)
16 | }
17 | }
--------------------------------------------------------------------------------
/test/tasks/Request3CallbacksKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.expectedResults
5 | import contributors.testRequestData
6 | import org.junit.Assert
7 | import org.junit.Test
8 |
9 | class Request3CallbacksKtTest {
10 | @Test
11 | fun testDataIsLoaded() {
12 | loadContributorsCallbacks(MockGithubService, testRequestData) {
13 | Assert.assertEquals(
14 | "Wrong result for 'loadContributorsCallbacks'",
15 | expectedResults.users, it
16 | )
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/test/tasks/Request4SuspendKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.expectedResults
5 | import contributors.testRequestData
6 | import kotlinx.coroutines.runBlocking
7 | import org.junit.Assert
8 | import org.junit.Test
9 |
10 | class Request4SuspendKtTest {
11 | @Test
12 | fun testSuspend() = runBlocking {
13 | val startTime = System.currentTimeMillis()
14 | val result = loadContributorsSuspend(MockGithubService, testRequestData)
15 | Assert.assertEquals("Wrong result for 'loadContributorsSuspend'", expectedResults.users, result)
16 | val totalTime = System.currentTimeMillis() - startTime
17 | /*
18 | // TODO: uncomment this assertion
19 | Assert.assertEquals(
20 | "The calls run consequently, so the total virtual time should be 4000 ms: " +
21 | "1000 for repos request plus (1000 + 1200 + 800) = 3000 for sequential contributors requests)",
22 | expectedResults.timeFromStart, totalTime
23 | )
24 | */
25 | Assert.assertTrue(
26 | "The calls run consequently, so the total time should be around 4000 ms: " +
27 | "1000 for repos request plus (1000 + 1200 + 800) = 3000 for sequential contributors requests)",
28 | totalTime in expectedResults.timeFromStart..(expectedResults.timeFromStart + 500)
29 | )
30 | }
31 | }
--------------------------------------------------------------------------------
/test/tasks/Request5ConcurrentKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.expectedConcurrentResults
5 | import contributors.testRequestData
6 | import kotlinx.coroutines.runBlocking
7 | import org.junit.Assert
8 | import org.junit.Test
9 |
10 | class Request5ConcurrentKtTest {
11 | @Test
12 | fun testConcurrent() = runBlocking {
13 | val startTime = System.currentTimeMillis()
14 | val result = loadContributorsConcurrent(MockGithubService, testRequestData)
15 | Assert.assertEquals("Wrong result for 'loadContributorsConcurrent'", expectedConcurrentResults.users, result)
16 | val totalTime = System.currentTimeMillis() - startTime
17 | /*
18 | // TODO: uncomment this assertion
19 | Assert.assertEquals(
20 | "The calls run concurrently, so the total virtual time should be 2200 ms: " +
21 | "1000 ms for repos request plus max(1000, 1200, 800) = 1200 ms for concurrent contributors requests)",
22 | expectedConcurrentResults.timeFromStart, totalTime
23 | )
24 | */
25 | Assert.assertTrue(
26 | "The calls run concurrently, so the total virtual time should be 2200 ms: " +
27 | "1000 ms for repos request plus max(1000, 1200, 800) = 1200 ms for concurrent contributors requests)",
28 | totalTime in expectedConcurrentResults.timeFromStart..(expectedConcurrentResults.timeFromStart + 500)
29 | )
30 | }
31 | }
--------------------------------------------------------------------------------
/test/tasks/Request6ProgressKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.progressResults
5 | import contributors.testRequestData
6 | import kotlinx.coroutines.runBlocking
7 | import org.junit.Assert
8 | import org.junit.Test
9 |
10 | class Request6ProgressKtTest {
11 | @Test
12 | fun testProgress() = runBlocking {
13 | val startTime = System.currentTimeMillis()
14 | var index = 0
15 | loadContributorsProgress(MockGithubService, testRequestData) {
16 | users, _ ->
17 | val expected = progressResults[index++]
18 | val time = System.currentTimeMillis() - startTime
19 | /*
20 | // TODO: uncomment this assertion
21 | Assert.assertEquals("Expected intermediate result after virtual ${expected.timeFromStart} ms:",
22 | expected.timeFromStart, time)
23 | */
24 | Assert.assertEquals("Wrong intermediate result after $time:", expected.users, users)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/test/tasks/Request7ChannelsKtTest.kt:
--------------------------------------------------------------------------------
1 | package tasks
2 |
3 | import contributors.MockGithubService
4 | import contributors.concurrentProgressResults
5 | import contributors.testRequestData
6 | import kotlinx.coroutines.runBlocking
7 | import org.junit.Assert
8 | import org.junit.Test
9 |
10 | class Request7ChannelsKtTest {
11 | @Test
12 | fun testChannels() = runBlocking {
13 | val startTime = System.currentTimeMillis()
14 | var index = 0
15 | loadContributorsChannels(MockGithubService, testRequestData) {
16 | users, _ ->
17 | val expected = concurrentProgressResults[index++]
18 | val time = System.currentTimeMillis() - startTime
19 | /*
20 | // TODO: uncomment this assertion
21 | Assert.assertEquals("Expected intermediate result after virtual ${expected.timeFromStart} ms:",
22 | expected.timeFromStart, time)
23 | */
24 | Assert.assertEquals("Wrong intermediate result after $time:", expected.users, users)
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------