[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: edgar-zigis\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".gitignore",
    "content": "*.iml\n.gradle\n/local.properties\n/.idea\n.DS_Store\n/build\n/captures\n.externalNativeBuild"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Coroutine Recipes\nPlayground for Kotlin Coroutines.<br/>\nReady to use ***IntelliJ IDEA*** project with basic explanations.\n\n```\n* Basic async/launch comparisons\n* Job/Deferred completion invocations & cancellations\n* Context tests\n* Basic & Supervisor scopes. Cancellation & exception handling.\n* Concurrent & serial tasks. Comparison with RxJava.\n* Critical section handling\n* Resource access from different threads\n* Channels, BroadcastChannels, ConflatedBroadcastChannels\n* Channel buffers\n* Differences between Channels and Flows\n* Basic Flow operators\n* State & Shared Flows\n* Callback & Channel Flows\n```\n\n**Project is under continuous development**\n"
  },
  {
    "path": "build.gradle",
    "content": "plugins {\n    id 'java'\n    id 'org.jetbrains.kotlin.jvm' version '1.7.10'\n    id \"org.jetbrains.kotlin.plugin.serialization\" version \"1.7.10\"\n}\n\ngroup 'CoroutineRecipes'\nversion '1.0-SNAPSHOT'\n\nrepositories {\n    mavenCentral()\n}\n\ndependencies {\n    implementation \"org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10\"\n    implementation 'io.reactivex.rxjava3:rxjava:3.0.0'\n    implementation \"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4\"\n    implementation \"org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0-RC\"\n\n    implementation \"io.ktor:ktor-client-java:2.0.3\"\n    implementation \"io.ktor:ktor-serialization-gson:2.0.3\"\n    implementation \"io.ktor:ktor-client-content-negotiation:2.0.3\"\n    implementation \"io.ktor:ktor-client-logging:2.0.3\"\n    testImplementation \"junit:junit:4.13.2\"\n}\n\ncompileKotlin {\n    kotlinOptions {\n        jvmTarget = JavaVersion.VERSION_1_8\n        freeCompilerArgs += \"-Xopt-in=kotlin.RequiresOptIn\"\n    }\n}\ncompileTestKotlin {\n    kotlinOptions {\n        jvmTarget = JavaVersion.VERSION_1_8\n        freeCompilerArgs += \"-Xopt-in=kotlin.RequiresOptIn\"\n    }\n}"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-7.5-bin.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n"
  },
  {
    "path": "gradle.properties",
    "content": "kotlin.code.style=official"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn () {\n    echo \"$*\"\n}\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\n  NONSTOP* )\n    nonstop=true\n    ;;\nesac\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Escape application args\nsave () {\n    for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n    echo \" \"\n}\nAPP_ARGS=$(save \"$@\")\n\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n\n# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\nif [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n  cd \"$(dirname \"$0\")\"\nfi\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windows variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "settings.gradle",
    "content": "rootProject.name = 'CoroutineRecipes'"
  },
  {
    "path": "src/main/kotlin/Basics.kt",
    "content": "import kotlinx.coroutines.*\n\n/*\n    Basic examples on differences between async/launch,\n    cancellations etc.\n */\n\n/*\n    NOTE! All of the examples use runBlocking which blocks the current thread. I never recommend using this as the\n    aim of the coroutines is to handle asynchronous tasks in the non-blocking way. But for testing purposes here\n    we will use runBlocking. Alternative would be using CoroutineScope.launch with Thread.sleep().\n    Normally, use CoroutineScope.launch for creating new tasks when you are working in the looper threads.\n */\n\nfun main() {\n    asyncVsLaunchSerial()\n    //asyncVsLaunchConcurrent()\n    //deferredCompletionInvocation()\n    //deferredCancellation()\n    //jobCompletionInvocation()\n    //jobCancellation()\n    //contextSwitching()\n    //contextPoolTest()\n}\n\n//  ****\n//  Task definitions\n//  ****\n\nprivate suspend fun someAsyncTask(iteration: Int): Int {\n    delay(3000L / iteration)\n    println(\"[Coroutines] Executed iteration: $iteration\")\n    return iteration\n}\n\n//  ****\n//  Async vs Launch\n//  ****\n\n/*\n    This shall output:\n    [Coroutines] Executed iteration: 1\n    [Coroutines] Executed iteration: 2\n    [Coroutines] Executed iteration: 1\n    [Coroutines] Executed iteration: 2\n\n    as the await() for Deferred and join() for Job both suspend the current scope and wait for completion\n */\nprivate fun asyncVsLaunchSerial() = runBlocking {\n    async { someAsyncTask(1) }.await()\n    launch { someAsyncTask(2) }.join()\n\n    launch { someAsyncTask(1) }.join()\n    async { someAsyncTask(2) }.await()\n}\n\n/*\n    This shall output:\n    [Coroutines] Executed iteration: 2\n    [Coroutines] Executed iteration: 2\n    [Coroutines] Executed iteration: 1\n    [Coroutines] Executed iteration: 1\n\n    as async without await() will perform in the same way like a simple launch\n */\nprivate fun asyncVsLaunchConcurrent() = runBlocking {\n    async { someAsyncTask(1) }\n    launch { someAsyncTask(2) }\n\n    launch { someAsyncTask(1) }\n    async { someAsyncTask(2) }\n}\n\n/*\n    The key differences are here:\n    a -> is Integer\n    b -> is Unit\n    c -> is Job\n    d -> is Deferred\n */\nprivate fun asyncVsLaunchResults() = runBlocking {\n    val a = async { someAsyncTask(1) }.await()\n    val b = launch { someAsyncTask(2) }.join()\n\n    val c = launch { someAsyncTask(1) }\n    val d = async { someAsyncTask(2) }\n}\n\n//  ****\n//  Async\n//  ****\n\n/*\n    Example on how to know about Deferred completion\n    exception will be null\n */\nprivate fun deferredCompletionInvocation() = runBlocking {\n    val someDeferred = async { someAsyncTask(1) }\n    someDeferred.invokeOnCompletion {\n        println(\"Deferred has been completed.\")\n    }\n    someDeferred.await()\n}\n\n/*\n    Example on how to know about Deferred completion when the exception is called\n    exception will be CancellationException which is the default one when the cancel() is called\n    You can supply any other exception extending the CancellationException\n    cancelAndJoin() can be used as alternative if waiting for cancellation completion is needed\n */\nprivate fun deferredCancellation() = runBlocking {\n    val someDeferred = async { someAsyncTask(1) }\n    someDeferred.cancel()\n    someDeferred.invokeOnCompletion {\n        println(\"Exception: $it\")\n    }\n    someDeferred.await()\n}\n\n//  ****\n//  Launch\n//  ****\n\n/*\n    Example on how to know about Job completion\n    exception will be null\n */\nprivate fun jobCompletionInvocation() = runBlocking {\n    val someJob = launch { someAsyncTask(1) }\n    someJob.invokeOnCompletion {\n        println(\"Job has been completed.\")\n    }\n}\n\n/*\n    Example on how to know about Job completion when the exception is called\n    exception will be CancellationException which is the default one when the cancel() is called\n    You can supply any other exception extending the CancellationException.\n    cancelAndJoin() can be used as alternative if waiting for cancellation completion is needed\n */\nprivate fun jobCancellation() = runBlocking {\n    val someJob = launch { someAsyncTask(1) }\n    someJob.cancel()\n    someJob.invokeOnCompletion {\n        println(\"Exception: $it\")\n    }\n}\n\n//  ****\n//  Contexts\n//  ****\n\n/*\n    Just some generic context switching\n */\nprivate fun contextSwitching() = runBlocking {\n    val value = withContext(Dispatchers.IO) {\n        someAsyncTask(2)\n    }\n    withContext(Dispatchers.Default) {\n        println(\"Context value: $value\")\n    }\n}\n\n/*\n    Deceiving example context switching\n    In this case 1,2,3,4,5 will be printed every time, because when using the same IO thread pool\n    The application does not switch threads. If there would be any other dispatcher (e.g. Unconfined)\n    then the result might be different\n */\n@OptIn(DelicateCoroutinesApi::class)\nprivate fun contextPoolTest() = runBlocking {\n    GlobalScope.launch(Dispatchers.IO) {\n        println(\"1\")\n        withContext(Dispatchers.IO) {\n            println(\"2\")\n            withContext(Dispatchers.IO) {\n                println(\"3\")\n            }\n            println(\"4\")\n        }\n        println(\"5\")\n    }\n    delay(100)\n}"
  },
  {
    "path": "src/main/kotlin/Channels.kt",
    "content": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.BroadcastChannel\nimport kotlinx.coroutines.channels.Channel\nimport kotlinx.coroutines.channels.ConflatedBroadcastChannel\nimport kotlinx.coroutines.channels.consumeEach\n\nfun main() {\n    simulateChannelWithoutBuffer()\n    //simulateChannelWithBuffer()\n    //simulateChannel()\n    //simulateBroadcastChannel()\n    //simulateConflatedBroadcastChannel()\n}\n\n//  ****\n//  Buffering examples\n//  ****\n\n/*\n    This method attempts to send 10 values, but it will send only single, because the capacity of the buffer is zero\n */\nfun simulateChannelWithoutBuffer() = runBlocking {\n    val channel = Channel<Int>(capacity = Channel.RENDEZVOUS)\n    val sender = launch { // launch sender coroutine\n        repeat(10) {\n            println(\"Sending $it\") // print before sending each element\n            channel.send(it) // will suspend when buffer is full\n        }\n    }\n    delay(1000)\n    sender.cancel()\n}\n\n/*\n    This method attempts to send 10 values, but it will send the 5 values because of the set buffer\n */\nfun simulateChannelWithBuffer() = runBlocking {\n    val channel = Channel<Int>(capacity = 4)\n    val sender = launch {\n        repeat(10) {\n            println(\"Sending $it\")\n            channel.send(it)\n        }\n    }\n    delay(1000)\n    sender.cancel()\n}\n\n//  ****\n//  Difference between Channel, BroadcastChannel, ConflatedBroadcastChannel\n//  ****\n\n/*\n    This shall print 1 and 3, because capacity is 1 and the element 2 will be ignored\n */\nfun simulateChannel() = runBlocking {\n    val channel = Channel<Int>(capacity = 1)\n\n    launch {\n        channel.trySend(1)\n        channel.trySend(2)\n    }\n\n    for (i in 0..1) {\n        launch {\n            channel.consumeEach {\n                println(\"Receiving something $it\")\n            }\n        }\n    }\n\n    launch {\n        channel.trySend(3)\n    }\n}\n\n/*\n    This shall print 3 and 3, because subscriber started listening after the values were sent to the channel\n    This works in the same way like RxJava PublishSubject\n */\n@OptIn(ObsoleteCoroutinesApi::class)\nfun simulateBroadcastChannel() = runBlocking {\n    val channel = BroadcastChannel<Int>(capacity = 1)\n\n    launch {\n        channel.trySend(1)\n        channel.trySend(2)\n    }\n\n    for (i in 0..1) {\n        launch {\n            channel.consumeEach {\n                println(\"Receiving something $it\")\n            }\n        }\n    }\n\n    launch {\n        channel.trySend(3)\n    }\n}\n\n/*\n    This shall print 2 and 3, because after subscription it will always emit the last value which was pushed to\n    the channel first.\n    This works in the same way like RxJava BehaviourSubject\n */\n@OptIn(ObsoleteCoroutinesApi::class)\nfun simulateConflatedBroadcastChannel() = runBlocking {\n    val channel = ConflatedBroadcastChannel<Int>()\n\n    launch {\n        channel.trySend(1)\n        channel.trySend(2)\n    }\n\n    launch {\n        channel.consumeEach {\n            println(\"Receiving something $it\")\n        }\n    }\n\n    launch {\n        channel.trySend(3)\n    }\n}"
  },
  {
    "path": "src/main/kotlin/ChannelsVsFlows.kt",
    "content": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.*\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.collect\nimport kotlinx.coroutines.flow.flow\nimport kotlin.system.measureTimeMillis\n\nfun main() {\n    runDummySolution()\n    //runChannelSolution()\n    //runFlowSolution()\n    //simulateDangerousChannelSituation()\n}\n\n//  ****\n//  Task definitions\n//  ****\n\nsuspend fun getResource(index: Int): Int {\n    delay(1000)\n    return index\n}\n\nfun Int.show() {\n    println(\"Hey, my name is Integer with index $this\")\n}\n\n//  ****\n//  Default dummy solution\n//  ****\n\n/*\n    This will wait 3 seconds and then immediately print all 3 resources\n */\nfun runDummySolution() = runBlocking {\n    val time = measureTimeMillis {\n        val resources = getListOfResources()\n        for (resource in resources) {\n            resource.show()\n        }\n    }\n    println(\"Ready in $time ms\")\n}\n\nsuspend fun getListOfResources(): List<Int> {\n    return listOf(\n        getResource(1),\n        getResource(2),\n        getResource(3)\n    )\n}\n\n//  ****\n//  Default channel solution\n//  ****\n\n/*\n    This will print resource every second. Total duration same as runDummySolution\n */\nfun runChannelSolution() = runBlocking {\n    val resourceChannel = channelOfResources()\n    val time = measureTimeMillis {\n        for (resource in resourceChannel) {\n            resource.show()\n        }\n    }\n    println(\"Ready in $time ms\")\n}\n\n@OptIn(ExperimentalCoroutinesApi::class)\nsuspend fun CoroutineScope.channelOfResources(): ReceiveChannel<Int> = produce {\n    send(getResource(1))\n    send(getResource(2))\n    send(getResource(3))\n}\n\n//  ****\n//  Default flow solution\n//  ****\n\n/*\n    This will do everything exactly like the runChannelSolution\n */\nfun runFlowSolution() = runBlocking {\n    val resourceFlow = flowOfResources()\n    val time = measureTimeMillis {\n        resourceFlow.collect { resource ->\n            resource.show()\n        }\n    }\n    println(\"Ready in $time ms\")\n}\n\nfun flowOfResources() : Flow<Int> = flow {\n    emit(getResource(1))\n    emit(getResource(2))\n    emit(getResource(3))\n}\n\n//  ****\n//  Key difference\n//  ****\n\n/*\n    val resourceChannel = channelOfResources() -> this already allocates resources\n    in this example it will print 1, then after resuming it will print 2, 3.\n    This means that the resources were not de-allocated and they were hanging in the air\n    potentially providing memory leaks.\n\n    val resourceFlow = flowOfResources() -> this does not allocate resources yet, until you start observing the results\n    in this example if replaced, this will print 1, then after resuming it will print 1, 2, 3.\n    This means that the resources were de-allocated after scope cancellation and it is safe to use in such\n    situations.\n */\nfun simulateDangerousChannelSituation() = runBlocking {\n    val shortLivedScope = CoroutineScope(Dispatchers.Default)\n    val resourceChannel = channelOfResources()\n\n    shortLivedScope.launch {\n        for (resource in resourceChannel) {\n            resource.show()\n        }\n    }\n\n    delay(1500)\n    shortLivedScope.cancel()\n\n    println(\"Scope has been canceled. Will resume channel again\")\n    delay(1000)\n\n    for (resource in resourceChannel) {\n        resource.show()\n    }\n}"
  },
  {
    "path": "src/main/kotlin/Concurrency.kt",
    "content": "\nimport io.reactivex.rxjava3.core.Observable\nimport io.reactivex.rxjava3.core.Single\nimport io.reactivex.rxjava3.schedulers.Schedulers\nimport kotlinx.coroutines.*\nimport kotlinx.coroutines.sync.Mutex\nimport kotlinx.coroutines.sync.withLock\nimport java.util.concurrent.TimeUnit\nimport kotlin.system.measureTimeMillis\n\n/*\n    Concurrency handling, serial & concurrent tasks, critical sections,\n    synchronization handling\n */\n\nfun main() {\n    runSerial()\n    //runSerialRxJava()\n    //runConcurrent()\n    //runConcurrentRxJava()\n    //runWithoutCriticalProtection()\n    //runWithCriticalProtection()\n    //syncSomething()\n    //Thread.sleep(10000)\n}\n\n//  ****\n//  Task definitions\n//  ****\n\nprivate suspend fun someAsyncTask(iteration: Int): Int {\n    delay(3000L / iteration)\n    println(\"[Coroutines] Executed iteration: $iteration\")\n    return iteration\n}\n\nprivate fun someAsyncTaskRxJava(iteration: Int): Single<Int> {\n    return Single.timer(3000L / iteration, TimeUnit.MILLISECONDS).map {\n        println(\"[RxJava] Executed iteration: $iteration\")\n        iteration\n    }\n}\n\n//  ****\n//  Serial tasks\n//  ****\n\n/*\n    This will execute all 3 tasks sequentially in specified order.\n    It should complete all tasks in 5.5 seconds in order 2, 1, 3\n\n    NOTE! This example was created to compare Deferred to Single.\n    The correct (and simple) usage of serial tasks would be:\n\n    private fun runSerial() = runBlocking {\n        someAsyncTask(2)\n        someAsyncTask(1)\n        someAsyncTask(3)\n    }\n */\n\nprivate fun runSerial() = runBlocking {\n    async { someAsyncTask(2) }.await()\n    async { someAsyncTask(1) }.await()\n    async { someAsyncTask(3) }.await()\n}\n\nprivate fun runSerialRxJava() {\n    someAsyncTaskRxJava(2).flatMap {\n        someAsyncTaskRxJava(1)\n    }.flatMap {\n        someAsyncTaskRxJava(3)\n    }\n        .subscribeOn(Schedulers.io())\n        .subscribe()\n    Thread.sleep(6000)\n}\n\n//  ****\n//  Concurrent tasks\n//  ****\n\n/*\n    This will execute all 3 tasks concurrently without specified order.\n    It should complete all tasks in 3 seconds in order of 3, 2, 1\n\n    NOTE! This example was created to compare Deferred to Single.\n    We do not need any result here, so\n    the correct (and simple) usage of concurrent tasks would be:\n\n    private fun runConcurrent() = runBlocking {\n        launch { someAsyncTask(2) }\n        launch { someAsyncTask(1) }\n        launch { someAsyncTask(3) }\n    }\n */\nprivate fun runConcurrent() = runBlocking {\n    awaitAll(\n        async { someAsyncTask(2) },\n        async { someAsyncTask(1) },\n        async { someAsyncTask(3) }\n    )\n}\n\nprivate fun runConcurrentRxJava() {\n    Observable.merge(\n        someAsyncTaskRxJava(2).toObservable(),\n        someAsyncTaskRxJava(1).toObservable(),\n        someAsyncTaskRxJava(3).toObservable()\n    )\n        .subscribeOn(Schedulers.io())\n        .subscribe()\n    Thread.sleep(4000)\n}\n\n//  ****\n//  Multithreading\n//  ****\n\nprivate var sharedValue = 0\n\n/*\n    This will output inconsistent Counter value\n */\n@OptIn(DelicateCoroutinesApi::class)\nprivate fun runWithoutCriticalProtection() = runBlocking {\n    GlobalScope.launch {\n        someErrorProneThreadLoop {\n            sharedValue++\n        }\n        println(\"Counter = $sharedValue\")\n    }\n    delay(500)\n}\n\n/*\n    This will always output 10000\n    Keep in mind not to nest mutexes like the synchronized blocks as it can result in easy deadlock\n */\n@OptIn(DelicateCoroutinesApi::class)\nprivate fun runWithCriticalProtection() = runBlocking {\n    GlobalScope.launch {\n        val mutex = Mutex()\n        someErrorProneThreadLoop {\n            mutex.withLock {\n                sharedValue++\n            }\n        }\n        println(\"Counter = $sharedValue\")\n    }\n    delay(500)\n}\n\nprivate suspend fun someErrorProneThreadLoop(action: suspend () -> Unit) {\n    val n = 100\n    val k = 100\n    val time = measureTimeMillis {\n        coroutineScope {\n            repeat(n) {\n                launch {\n                    repeat(k) { action() }\n                }\n            }\n        }\n    }\n    println(\"Completed ${n * k} actions in $time ms\")\n}\n\n//  ****\n//  Synchronization examples\n//  ****\n\nvar syncDeferred: Deferred<Boolean>? = null\nval syncMutex = Mutex()\n\n/*\n    The aim is not to call the synchronization code until the previous call is finished\n    and reuse the result of the previous call\n */\nprivate suspend fun synchronizeSomething(value: Int): Deferred<Boolean> = coroutineScope {\n    syncMutex.withLock {\n        syncDeferred?.let {\n            return@coroutineScope it\n        }\n        return@coroutineScope async {\n            delay(1000)\n            println(\"I return things nicely $value\")\n            syncDeferred = null\n            true\n        }.also {\n            syncDeferred = it\n        }\n    }\n}\n\n/*\n    This shall output:\n    I return things nicely 1\n    I return things nicely 3\n\n    Removing mutex from synchronizeSomething will result in:\n    I return things nicely 1\n    I return things nicely 2\n    I return things nicely 3\n */\nprivate fun syncSomething() = runBlocking {\n    launch {\n        synchronizeSomething(1).await()\n    }\n    launch {\n        synchronizeSomething(2).await()\n    }\n    launch {\n        delay(1500)\n        synchronizeSomething(3).await()\n    }\n}"
  },
  {
    "path": "src/main/kotlin/Flows.kt",
    "content": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.awaitClose\nimport kotlinx.coroutines.flow.*\n\nfun main() {\n    testBasicFlowOperators()\n    //testBasicFlowCollect()\n    //testBasicFlowDistinctCollection()\n    //testBasicFlowDebounceCollection()\n    //testBasicFlowTakeCollection()\n    //testBasicFlowGargantuanCollection()\n    //testSharedFlow()\n    //testStateFlow()\n    //testDummyFlowWithConcurrentEmissions()\n    //testCallbackFlowWithConcurrentEmissions()\n    //testChannelFlowWithConcurrentEmissions()\n}\n\n//  ****\n//  Basic Flow operators\n//  ****\n\nfun basicFlow(): Flow<Int> = flow {\n    for (i in 0 until 3) {\n        emit(i)\n        delay(100)\n        emit(i)\n    }\n}.flowOn(Dispatchers.IO)\n\nfun basicFlowWithException(): Flow<Int> = flow {\n    for (i in 0 until 3) {\n        emit(i)\n        delay(100)\n        emit(i)\n        if (i == 1) throw Error()\n    }\n}.flowOn(Dispatchers.IO)\n\n/*\n    This will output 'started', 0 0 1 1 'finished' 'exception'\n    if catch is not used -> process will crash and exception will be passed upstream\n */\nfun testBasicFlowOperators() = runBlocking {\n    basicFlowWithException().onEach {\n        println(\"BasicFlow emitted value: $it\")\n    }.onStart {\n        println(\"BasicFlow has started its work\")\n    }.onCompletion {\n        println(\"BasicFlow has finished its work\")\n    }.catch {\n        println(\"BasicFlow has an exception $it\")\n    }.launchIn(this)\n}\n\n/*\n    This will output 0 0 1 1 and then process will crash\n    Exception is passed upstream\n */\nfun testBasicFlowCollect() = runBlocking {\n    basicFlowWithException().collect {\n        println(\"BasicFlowCollect emitted value: $it\")\n    }\n}\n\n/*\n    This will output 0 1 2\n    distinctUntilChanged ignores any duplicates\n */\nfun testBasicFlowDistinctCollection() = runBlocking {\n    basicFlow().distinctUntilChanged().collect {\n        println(\"BasicFlowDistinctCollect emitted value: $it\")\n    }\n}\n\n/*\n    This will output 0 1 2 2\n    debounce is ignoring any values emitted faster than the previous one\n */\n@OptIn(FlowPreview::class)\nfun testBasicFlowDebounceCollection() = runBlocking {\n    basicFlow().debounce(80).collect {\n        println(\"BasicFlowDebounceCollect emitted value: $it\")\n    }\n}\n\n/*\n    This will output 0 0 1\n    take will just take first 3 elements from the flow and finish\n */\nfun testBasicFlowTakeCollection() = runBlocking {\n    basicFlow().take(3).collect {\n        println(\"BasicFlowDebounceCollect emitted value: $it\")\n    }\n}\n\n/*\n    This will output 0 0 1 1 2 2 sum 12\n    This is just a simple operator display\n */\nfun testBasicFlowGargantuanCollection() = runBlocking {\n    val someWeirdSum = basicFlow().onEach {\n        delay(200)\n        println(\"Computing $it\")\n    }.filter {\n        it % 2 == 0\n    }.map {\n        it + 2\n    }.reduce { accumulator, value ->\n        accumulator + value\n    }\n    println(\"SomeGargantuanSum: $someWeirdSum\")\n}\n\n//  ****\n//  Shared/State Flow\n//  ****\n\n/*\n    replay represents the number of values emitted to new subscribers\n */\nval sharedFlow = MutableSharedFlow<Int>(replay = 1)\nval stateFlow = MutableStateFlow(69)\n\n/*\n    This will output 0 0 1 1 2 2\n    Basically this acts like a channel and outputs everything\n    Try removing delays though and it will output less values,\n    because subscriber thread is too slow to listen to changes.\n    SharedFlow is a hot replacement for BroadcastChannel\n */\nfun testSharedFlow() = runBlocking {\n    sharedFlow.asSharedFlow().onEach {\n        println(\"SharedFlow value: $it\")\n    }.launchIn(this)\n\n    for (i in 0 until 3) {\n        sharedFlow.tryEmit(i)\n        delay(100)\n        sharedFlow.tryEmit(i)\n        delay(100)\n    }\n}\n\n/*\n    This will output 0 1 2\n    StateFlow is used to specifically work with states as it will only emit new states.\n    StateFlow == SharedFlow with distinctUntilChanged applied.\n    This is a perfect replacement for LiveData\n */\nfun testStateFlow() = runBlocking {\n    stateFlow.asStateFlow().onEach {\n        println(\"StateFlow value: $it\")\n    }.launchIn(this)\n\n    for (i in 0 until 3) {\n        stateFlow.value = i\n        delay(100)\n        stateFlow.value = i\n        delay(100)\n    }\n}\n\n//  ****\n//  Callback/Channel Flow\n//  ****\n\n/*\n    The following methods represent an attempt to provide some callback values from different threads\n    1. Using generic Flow\n    2. CallbackFlow\n    3. ChannelFlow\n */\n@OptIn(DelicateCoroutinesApi::class)\nfun dummyFlow(): Flow<Int> = flow {\n    GlobalScope.launch {\n        emit(1)\n        emit(2)\n    }\n    delay(100)\n}\n\n@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)\nfun callbackFlow(): Flow<Int> = callbackFlow {\n    GlobalScope.launch {\n        trySend(1)\n        trySend(2)\n        close()\n    }\n    delay(100)\n    awaitClose { cancel() }\n}\n\n@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)\nfun channelFlow(): Flow<Int> = channelFlow {\n    GlobalScope.launch {\n        trySend(1)\n        trySend(2)\n        close()\n    }\n    delay(100)\n    awaitClose { cancel() }\n}\n\n/*\n    This will crash. Because emission from any other or coroutine is not allowed.\n    This can't be used for callbacks.\n */\nfun testDummyFlowWithConcurrentEmissions() = runBlocking {\n    dummyFlow().collect {\n        println(\"DummyFlow value: $it\")\n    }\n}\n\n/*\n    This will work fine and emit 1 2. CallbackFlow is designed to deal specifically with callbacks.\n    Great replacement for custom Rx Callback Observables\n */\nfun testCallbackFlowWithConcurrentEmissions() = runBlocking {\n    callbackFlow().collect {\n        println(\"CallbackFlow value: $it\")\n    }\n}\n\n/*\n    This will work fine and emit 1 2, same like callbackFlow\n    What's the difference? Try removing awaitClose from callbackFlow and it will crash\n    channelFlow - won't. Basically the difference is very minor, callbackFlow is more secure\n    awaitClose should be used to close any resources (like observers).\n    Also, do not forget to call close() which notifies flow that there is nothing to listen to.\n    close() should be called when the final action was performed.\n */\nfun testChannelFlowWithConcurrentEmissions() = runBlocking {\n    channelFlow().collect {\n        println(\"ChannelFlow value: $it\")\n    }\n}"
  },
  {
    "path": "src/main/kotlin/Scopes.kt",
    "content": "import kotlinx.coroutines.*\n\n/*\n    Coroutine scope related examples\n */\n\nfun main() {\n    runDefaultScope()\n    //runSupervisorScope()\n    //testScopeCancellation()\n    //testScopeCancellationWithSupervisor()\n}\n\n//  ****\n//  Task definitions\n//  ****\n\nprivate suspend fun someAsyncTask(iteration: Int): Int {\n    delay(3000L / iteration)\n    println(\"[Coroutines] Executed iteration: $iteration\")\n    if (iteration % 2 == 0) {\n        throw IllegalStateException()\n    }\n    return iteration\n}\n\n//  ****\n//  Default scope\n//  ****\n\n/*\n    Example with generic scope.\n    All tasks after first exception will be cancelled\n */\nprivate fun runDefaultScope() = runBlocking {\n    coroutineScope {\n        launch {\n            someAsyncTask(1)\n        }\n        launch {\n            someAsyncTask(2)\n        }\n        launch {\n            someAsyncTask(3)\n        }\n    }\n}\n\n//  ****\n//  Supervisor scope\n//  ****\n\n/*\n    Example with supervisor scope.\n    All tasks will be executed despite the exceptions\n */\nprivate fun runSupervisorScope() = runBlocking {\n    supervisorScope {\n        launch {\n            someAsyncTask(1)\n        }\n        launch {\n            someAsyncTask(2)\n        }\n        launch {\n            someAsyncTask(3)\n        }\n    }\n}\n\n//  ****\n//  Scope cancellation\n//  ****\n\n/*\n    Example with generic scope.\n    Scope will be cancelled after method with iteration 3 will be executed.\n    Method with iteration 1 won't be executed\n */\nprivate fun testScopeCancellation() = runBlocking {\n    val scope = CoroutineScope(Dispatchers.IO)\n\n    scope.launch {\n        someAsyncTask(1)\n    }\n    scope.launch {\n        someAsyncTask(3)\n        scope.cancel()\n    }\n    scope.launch {\n        someAsyncTask(5)\n    }\n\n    delay(1500)\n}\n\n/*\n    Deceiving example with supplied supervisor job.\n    No tasks will be cancelled. For proper cancellation the job itself should be cancelled.\n */\nprivate fun testScopeCancellationWithSupervisor() = runBlocking {\n    val job = SupervisorJob()\n    val scope = CoroutineScope(Dispatchers.IO)\n\n    scope.launch(job) {\n        someAsyncTask(1)\n    }\n    scope.launch(job) {\n        someAsyncTask(3)\n        scope.cancel()\n    }\n    scope.launch(job) {\n        someAsyncTask(5)\n    }\n\n    delay(4000)\n}"
  },
  {
    "path": "src/main/kotlin/shared/exceptions/ApiError.kt",
    "content": "package shared.exceptions\n\nimport kotlinx.serialization.Serializable\n\n@Serializable\ndata class ApiError(\n    override val message: String\n) : Error()"
  },
  {
    "path": "src/main/kotlin/shared/networking/BaseApiClient.kt",
    "content": "package shared.networking\n\ninterface BaseApiClient"
  },
  {
    "path": "src/main/kotlin/shared/networking/BaseApiFactory.kt",
    "content": "package shared.networking\n\nimport io.ktor.client.*\nimport io.ktor.client.engine.java.*\nimport io.ktor.client.plugins.*\nimport io.ktor.client.plugins.contentnegotiation.*\nimport io.ktor.client.plugins.logging.*\nimport io.ktor.client.request.*\nimport io.ktor.client.statement.*\nimport io.ktor.http.*\nimport io.ktor.serialization.gson.*\nimport kotlinx.serialization.json.Json\nimport shared.exceptions.ApiError\n\nabstract class BaseApiFactory<T : BaseApiClient>(\n    private val baseUrl: String,\n    private val userAgent: String,\n    private val timeout: Int? = null,\n    private val logLevel: LogLevel = LogLevel.BODY\n) {\n\n    private val json = Json {\n        ignoreUnknownKeys = true\n    }\n\n    abstract fun createClient(): T\n\n    protected fun createKtorClient(): HttpClient {\n        return HttpClient(Java) {\n\n            defaultRequest {\n                url {\n                    takeFrom(URLBuilder().takeFrom(baseUrl).apply {\n                        encodedPath += encodedPath\n                    })\n                }\n                header(HttpHeaders.ContentType, ContentType.Application.Json)\n                header(HttpHeaders.UserAgent, userAgent)\n            }\n\n            HttpResponseValidator {\n                handleResponseException {\n                    handleRequestError(it)\n                }\n            }\n\n            timeout?.let {\n                install(HttpTimeout) {\n                    requestTimeoutMillis = it.toLong()\n                    socketTimeoutMillis = it.toLong()\n                    connectTimeoutMillis = it.toLong()\n                }\n            }\n\n            install(ContentNegotiation) {\n                gson {\n                    serializeNulls()\n                }\n            }\n\n            install(Logging) {\n                logger = Logger.ANDROID\n                level = logLevel\n            }\n        }\n    }\n\n    private suspend fun handleRequestError(requestError: Throwable) {\n        val errorToThrow = when (requestError) {\n            is ClientRequestException -> {\n                val errorString = requestError.response.bodyAsText()\n                try {\n                    json.decodeFromString(ApiError.serializer(), errorString)\n                } catch (e: Exception) {\n                    ApiError(message = requestError.message)\n                }\n            }\n            else -> {\n                ApiError(message = requestError.message ?: \"\")\n            }\n        }\n        throw errorToThrow\n    }\n}"
  }
]