Full Code of edgar-zigis/CoroutineRecipes for AI

master 50665314b8a7 cached
20 files
48.3 KB
12.1k tokens
1 requests
Download .txt
Repository: edgar-zigis/CoroutineRecipes
Branch: master
Commit: 50665314b8a7
Files: 20
Total size: 48.3 KB

Directory structure:
gitextract_zjhzyaig/

├── .github/
│   └── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src/
    └── main/
        └── kotlin/
            ├── Basics.kt
            ├── Channels.kt
            ├── ChannelsVsFlows.kt
            ├── Concurrency.kt
            ├── Flows.kt
            ├── Scopes.kt
            └── shared/
                ├── exceptions/
                │   └── ApiError.kt
                └── networking/
                    ├── BaseApiClient.kt
                    └── BaseApiFactory.kt

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: edgar-zigis
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


================================================
FILE: .gitignore
================================================
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# Coroutine Recipes
Playground for Kotlin Coroutines.<br/>
Ready to use ***IntelliJ IDEA*** project with basic explanations.

```
* Basic async/launch comparisons
* Job/Deferred completion invocations & cancellations
* Context tests
* Basic & Supervisor scopes. Cancellation & exception handling.
* Concurrent & serial tasks. Comparison with RxJava.
* Critical section handling
* Resource access from different threads
* Channels, BroadcastChannels, ConflatedBroadcastChannels
* Channel buffers
* Differences between Channels and Flows
* Basic Flow operators
* State & Shared Flows
* Callback & Channel Flows
```

**Project is under continuous development**


================================================
FILE: build.gradle
================================================
plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.7.10'
    id "org.jetbrains.kotlin.plugin.serialization" version "1.7.10"
}

group 'CoroutineRecipes'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10"
    implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0-RC"

    implementation "io.ktor:ktor-client-java:2.0.3"
    implementation "io.ktor:ktor-serialization-gson:2.0.3"
    implementation "io.ktor:ktor-client-content-negotiation:2.0.3"
    implementation "io.ktor:ktor-client-logging:2.0.3"
    testImplementation "junit:junit:4.13.2"
}

compileKotlin {
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8
        freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8
        freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
    }
}

================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists


================================================
FILE: gradle.properties
================================================
kotlin.code.style=official

================================================
FILE: gradlew
================================================
#!/usr/bin/env sh

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
    echo "$*"
}

die () {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Escape application args
save () {
    for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
    echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
  cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"


================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windows variants

if not "%OS%" == "Windows_NT" goto win9xME_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: settings.gradle
================================================
rootProject.name = 'CoroutineRecipes'

================================================
FILE: src/main/kotlin/Basics.kt
================================================
import kotlinx.coroutines.*

/*
    Basic examples on differences between async/launch,
    cancellations etc.
 */

/*
    NOTE! All of the examples use runBlocking which blocks the current thread. I never recommend using this as the
    aim of the coroutines is to handle asynchronous tasks in the non-blocking way. But for testing purposes here
    we will use runBlocking. Alternative would be using CoroutineScope.launch with Thread.sleep().
    Normally, use CoroutineScope.launch for creating new tasks when you are working in the looper threads.
 */

fun main() {
    asyncVsLaunchSerial()
    //asyncVsLaunchConcurrent()
    //deferredCompletionInvocation()
    //deferredCancellation()
    //jobCompletionInvocation()
    //jobCancellation()
    //contextSwitching()
    //contextPoolTest()
}

//  ****
//  Task definitions
//  ****

private suspend fun someAsyncTask(iteration: Int): Int {
    delay(3000L / iteration)
    println("[Coroutines] Executed iteration: $iteration")
    return iteration
}

//  ****
//  Async vs Launch
//  ****

/*
    This shall output:
    [Coroutines] Executed iteration: 1
    [Coroutines] Executed iteration: 2
    [Coroutines] Executed iteration: 1
    [Coroutines] Executed iteration: 2

    as the await() for Deferred and join() for Job both suspend the current scope and wait for completion
 */
private fun asyncVsLaunchSerial() = runBlocking {
    async { someAsyncTask(1) }.await()
    launch { someAsyncTask(2) }.join()

    launch { someAsyncTask(1) }.join()
    async { someAsyncTask(2) }.await()
}

/*
    This shall output:
    [Coroutines] Executed iteration: 2
    [Coroutines] Executed iteration: 2
    [Coroutines] Executed iteration: 1
    [Coroutines] Executed iteration: 1

    as async without await() will perform in the same way like a simple launch
 */
private fun asyncVsLaunchConcurrent() = runBlocking {
    async { someAsyncTask(1) }
    launch { someAsyncTask(2) }

    launch { someAsyncTask(1) }
    async { someAsyncTask(2) }
}

/*
    The key differences are here:
    a -> is Integer
    b -> is Unit
    c -> is Job
    d -> is Deferred
 */
private fun asyncVsLaunchResults() = runBlocking {
    val a = async { someAsyncTask(1) }.await()
    val b = launch { someAsyncTask(2) }.join()

    val c = launch { someAsyncTask(1) }
    val d = async { someAsyncTask(2) }
}

//  ****
//  Async
//  ****

/*
    Example on how to know about Deferred completion
    exception will be null
 */
private fun deferredCompletionInvocation() = runBlocking {
    val someDeferred = async { someAsyncTask(1) }
    someDeferred.invokeOnCompletion {
        println("Deferred has been completed.")
    }
    someDeferred.await()
}

/*
    Example on how to know about Deferred completion when the exception is called
    exception will be CancellationException which is the default one when the cancel() is called
    You can supply any other exception extending the CancellationException
    cancelAndJoin() can be used as alternative if waiting for cancellation completion is needed
 */
private fun deferredCancellation() = runBlocking {
    val someDeferred = async { someAsyncTask(1) }
    someDeferred.cancel()
    someDeferred.invokeOnCompletion {
        println("Exception: $it")
    }
    someDeferred.await()
}

//  ****
//  Launch
//  ****

/*
    Example on how to know about Job completion
    exception will be null
 */
private fun jobCompletionInvocation() = runBlocking {
    val someJob = launch { someAsyncTask(1) }
    someJob.invokeOnCompletion {
        println("Job has been completed.")
    }
}

/*
    Example on how to know about Job completion when the exception is called
    exception will be CancellationException which is the default one when the cancel() is called
    You can supply any other exception extending the CancellationException.
    cancelAndJoin() can be used as alternative if waiting for cancellation completion is needed
 */
private fun jobCancellation() = runBlocking {
    val someJob = launch { someAsyncTask(1) }
    someJob.cancel()
    someJob.invokeOnCompletion {
        println("Exception: $it")
    }
}

//  ****
//  Contexts
//  ****

/*
    Just some generic context switching
 */
private fun contextSwitching() = runBlocking {
    val value = withContext(Dispatchers.IO) {
        someAsyncTask(2)
    }
    withContext(Dispatchers.Default) {
        println("Context value: $value")
    }
}

/*
    Deceiving example context switching
    In this case 1,2,3,4,5 will be printed every time, because when using the same IO thread pool
    The application does not switch threads. If there would be any other dispatcher (e.g. Unconfined)
    then the result might be different
 */
@OptIn(DelicateCoroutinesApi::class)
private fun contextPoolTest() = runBlocking {
    GlobalScope.launch(Dispatchers.IO) {
        println("1")
        withContext(Dispatchers.IO) {
            println("2")
            withContext(Dispatchers.IO) {
                println("3")
            }
            println("4")
        }
        println("5")
    }
    delay(100)
}

================================================
FILE: src/main/kotlin/Channels.kt
================================================
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.channels.consumeEach

fun main() {
    simulateChannelWithoutBuffer()
    //simulateChannelWithBuffer()
    //simulateChannel()
    //simulateBroadcastChannel()
    //simulateConflatedBroadcastChannel()
}

//  ****
//  Buffering examples
//  ****

/*
    This method attempts to send 10 values, but it will send only single, because the capacity of the buffer is zero
 */
fun simulateChannelWithoutBuffer() = runBlocking {
    val channel = Channel<Int>(capacity = Channel.RENDEZVOUS)
    val sender = launch { // launch sender coroutine
        repeat(10) {
            println("Sending $it") // print before sending each element
            channel.send(it) // will suspend when buffer is full
        }
    }
    delay(1000)
    sender.cancel()
}

/*
    This method attempts to send 10 values, but it will send the 5 values because of the set buffer
 */
fun simulateChannelWithBuffer() = runBlocking {
    val channel = Channel<Int>(capacity = 4)
    val sender = launch {
        repeat(10) {
            println("Sending $it")
            channel.send(it)
        }
    }
    delay(1000)
    sender.cancel()
}

//  ****
//  Difference between Channel, BroadcastChannel, ConflatedBroadcastChannel
//  ****

/*
    This shall print 1 and 3, because capacity is 1 and the element 2 will be ignored
 */
fun simulateChannel() = runBlocking {
    val channel = Channel<Int>(capacity = 1)

    launch {
        channel.trySend(1)
        channel.trySend(2)
    }

    for (i in 0..1) {
        launch {
            channel.consumeEach {
                println("Receiving something $it")
            }
        }
    }

    launch {
        channel.trySend(3)
    }
}

/*
    This shall print 3 and 3, because subscriber started listening after the values were sent to the channel
    This works in the same way like RxJava PublishSubject
 */
@OptIn(ObsoleteCoroutinesApi::class)
fun simulateBroadcastChannel() = runBlocking {
    val channel = BroadcastChannel<Int>(capacity = 1)

    launch {
        channel.trySend(1)
        channel.trySend(2)
    }

    for (i in 0..1) {
        launch {
            channel.consumeEach {
                println("Receiving something $it")
            }
        }
    }

    launch {
        channel.trySend(3)
    }
}

/*
    This shall print 2 and 3, because after subscription it will always emit the last value which was pushed to
    the channel first.
    This works in the same way like RxJava BehaviourSubject
 */
@OptIn(ObsoleteCoroutinesApi::class)
fun simulateConflatedBroadcastChannel() = runBlocking {
    val channel = ConflatedBroadcastChannel<Int>()

    launch {
        channel.trySend(1)
        channel.trySend(2)
    }

    launch {
        channel.consumeEach {
            println("Receiving something $it")
        }
    }

    launch {
        channel.trySend(3)
    }
}

================================================
FILE: src/main/kotlin/ChannelsVsFlows.kt
================================================
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlin.system.measureTimeMillis

fun main() {
    runDummySolution()
    //runChannelSolution()
    //runFlowSolution()
    //simulateDangerousChannelSituation()
}

//  ****
//  Task definitions
//  ****

suspend fun getResource(index: Int): Int {
    delay(1000)
    return index
}

fun Int.show() {
    println("Hey, my name is Integer with index $this")
}

//  ****
//  Default dummy solution
//  ****

/*
    This will wait 3 seconds and then immediately print all 3 resources
 */
fun runDummySolution() = runBlocking {
    val time = measureTimeMillis {
        val resources = getListOfResources()
        for (resource in resources) {
            resource.show()
        }
    }
    println("Ready in $time ms")
}

suspend fun getListOfResources(): List<Int> {
    return listOf(
        getResource(1),
        getResource(2),
        getResource(3)
    )
}

//  ****
//  Default channel solution
//  ****

/*
    This will print resource every second. Total duration same as runDummySolution
 */
fun runChannelSolution() = runBlocking {
    val resourceChannel = channelOfResources()
    val time = measureTimeMillis {
        for (resource in resourceChannel) {
            resource.show()
        }
    }
    println("Ready in $time ms")
}

@OptIn(ExperimentalCoroutinesApi::class)
suspend fun CoroutineScope.channelOfResources(): ReceiveChannel<Int> = produce {
    send(getResource(1))
    send(getResource(2))
    send(getResource(3))
}

//  ****
//  Default flow solution
//  ****

/*
    This will do everything exactly like the runChannelSolution
 */
fun runFlowSolution() = runBlocking {
    val resourceFlow = flowOfResources()
    val time = measureTimeMillis {
        resourceFlow.collect { resource ->
            resource.show()
        }
    }
    println("Ready in $time ms")
}

fun flowOfResources() : Flow<Int> = flow {
    emit(getResource(1))
    emit(getResource(2))
    emit(getResource(3))
}

//  ****
//  Key difference
//  ****

/*
    val resourceChannel = channelOfResources() -> this already allocates resources
    in this example it will print 1, then after resuming it will print 2, 3.
    This means that the resources were not de-allocated and they were hanging in the air
    potentially providing memory leaks.

    val resourceFlow = flowOfResources() -> this does not allocate resources yet, until you start observing the results
    in this example if replaced, this will print 1, then after resuming it will print 1, 2, 3.
    This means that the resources were de-allocated after scope cancellation and it is safe to use in such
    situations.
 */
fun simulateDangerousChannelSituation() = runBlocking {
    val shortLivedScope = CoroutineScope(Dispatchers.Default)
    val resourceChannel = channelOfResources()

    shortLivedScope.launch {
        for (resource in resourceChannel) {
            resource.show()
        }
    }

    delay(1500)
    shortLivedScope.cancel()

    println("Scope has been canceled. Will resume channel again")
    delay(1000)

    for (resource in resourceChannel) {
        resource.show()
    }
}

================================================
FILE: src/main/kotlin/Concurrency.kt
================================================

import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.TimeUnit
import kotlin.system.measureTimeMillis

/*
    Concurrency handling, serial & concurrent tasks, critical sections,
    synchronization handling
 */

fun main() {
    runSerial()
    //runSerialRxJava()
    //runConcurrent()
    //runConcurrentRxJava()
    //runWithoutCriticalProtection()
    //runWithCriticalProtection()
    //syncSomething()
    //Thread.sleep(10000)
}

//  ****
//  Task definitions
//  ****

private suspend fun someAsyncTask(iteration: Int): Int {
    delay(3000L / iteration)
    println("[Coroutines] Executed iteration: $iteration")
    return iteration
}

private fun someAsyncTaskRxJava(iteration: Int): Single<Int> {
    return Single.timer(3000L / iteration, TimeUnit.MILLISECONDS).map {
        println("[RxJava] Executed iteration: $iteration")
        iteration
    }
}

//  ****
//  Serial tasks
//  ****

/*
    This will execute all 3 tasks sequentially in specified order.
    It should complete all tasks in 5.5 seconds in order 2, 1, 3

    NOTE! This example was created to compare Deferred to Single.
    The correct (and simple) usage of serial tasks would be:

    private fun runSerial() = runBlocking {
        someAsyncTask(2)
        someAsyncTask(1)
        someAsyncTask(3)
    }
 */

private fun runSerial() = runBlocking {
    async { someAsyncTask(2) }.await()
    async { someAsyncTask(1) }.await()
    async { someAsyncTask(3) }.await()
}

private fun runSerialRxJava() {
    someAsyncTaskRxJava(2).flatMap {
        someAsyncTaskRxJava(1)
    }.flatMap {
        someAsyncTaskRxJava(3)
    }
        .subscribeOn(Schedulers.io())
        .subscribe()
    Thread.sleep(6000)
}

//  ****
//  Concurrent tasks
//  ****

/*
    This will execute all 3 tasks concurrently without specified order.
    It should complete all tasks in 3 seconds in order of 3, 2, 1

    NOTE! This example was created to compare Deferred to Single.
    We do not need any result here, so
    the correct (and simple) usage of concurrent tasks would be:

    private fun runConcurrent() = runBlocking {
        launch { someAsyncTask(2) }
        launch { someAsyncTask(1) }
        launch { someAsyncTask(3) }
    }
 */
private fun runConcurrent() = runBlocking {
    awaitAll(
        async { someAsyncTask(2) },
        async { someAsyncTask(1) },
        async { someAsyncTask(3) }
    )
}

private fun runConcurrentRxJava() {
    Observable.merge(
        someAsyncTaskRxJava(2).toObservable(),
        someAsyncTaskRxJava(1).toObservable(),
        someAsyncTaskRxJava(3).toObservable()
    )
        .subscribeOn(Schedulers.io())
        .subscribe()
    Thread.sleep(4000)
}

//  ****
//  Multithreading
//  ****

private var sharedValue = 0

/*
    This will output inconsistent Counter value
 */
@OptIn(DelicateCoroutinesApi::class)
private fun runWithoutCriticalProtection() = runBlocking {
    GlobalScope.launch {
        someErrorProneThreadLoop {
            sharedValue++
        }
        println("Counter = $sharedValue")
    }
    delay(500)
}

/*
    This will always output 10000
    Keep in mind not to nest mutexes like the synchronized blocks as it can result in easy deadlock
 */
@OptIn(DelicateCoroutinesApi::class)
private fun runWithCriticalProtection() = runBlocking {
    GlobalScope.launch {
        val mutex = Mutex()
        someErrorProneThreadLoop {
            mutex.withLock {
                sharedValue++
            }
        }
        println("Counter = $sharedValue")
    }
    delay(500)
}

private suspend fun someErrorProneThreadLoop(action: suspend () -> Unit) {
    val n = 100
    val k = 100
    val time = measureTimeMillis {
        coroutineScope {
            repeat(n) {
                launch {
                    repeat(k) { action() }
                }
            }
        }
    }
    println("Completed ${n * k} actions in $time ms")
}

//  ****
//  Synchronization examples
//  ****

var syncDeferred: Deferred<Boolean>? = null
val syncMutex = Mutex()

/*
    The aim is not to call the synchronization code until the previous call is finished
    and reuse the result of the previous call
 */
private suspend fun synchronizeSomething(value: Int): Deferred<Boolean> = coroutineScope {
    syncMutex.withLock {
        syncDeferred?.let {
            return@coroutineScope it
        }
        return@coroutineScope async {
            delay(1000)
            println("I return things nicely $value")
            syncDeferred = null
            true
        }.also {
            syncDeferred = it
        }
    }
}

/*
    This shall output:
    I return things nicely 1
    I return things nicely 3

    Removing mutex from synchronizeSomething will result in:
    I return things nicely 1
    I return things nicely 2
    I return things nicely 3
 */
private fun syncSomething() = runBlocking {
    launch {
        synchronizeSomething(1).await()
    }
    launch {
        synchronizeSomething(2).await()
    }
    launch {
        delay(1500)
        synchronizeSomething(3).await()
    }
}

================================================
FILE: src/main/kotlin/Flows.kt
================================================
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*

fun main() {
    testBasicFlowOperators()
    //testBasicFlowCollect()
    //testBasicFlowDistinctCollection()
    //testBasicFlowDebounceCollection()
    //testBasicFlowTakeCollection()
    //testBasicFlowGargantuanCollection()
    //testSharedFlow()
    //testStateFlow()
    //testDummyFlowWithConcurrentEmissions()
    //testCallbackFlowWithConcurrentEmissions()
    //testChannelFlowWithConcurrentEmissions()
}

//  ****
//  Basic Flow operators
//  ****

fun basicFlow(): Flow<Int> = flow {
    for (i in 0 until 3) {
        emit(i)
        delay(100)
        emit(i)
    }
}.flowOn(Dispatchers.IO)

fun basicFlowWithException(): Flow<Int> = flow {
    for (i in 0 until 3) {
        emit(i)
        delay(100)
        emit(i)
        if (i == 1) throw Error()
    }
}.flowOn(Dispatchers.IO)

/*
    This will output 'started', 0 0 1 1 'finished' 'exception'
    if catch is not used -> process will crash and exception will be passed upstream
 */
fun testBasicFlowOperators() = runBlocking {
    basicFlowWithException().onEach {
        println("BasicFlow emitted value: $it")
    }.onStart {
        println("BasicFlow has started its work")
    }.onCompletion {
        println("BasicFlow has finished its work")
    }.catch {
        println("BasicFlow has an exception $it")
    }.launchIn(this)
}

/*
    This will output 0 0 1 1 and then process will crash
    Exception is passed upstream
 */
fun testBasicFlowCollect() = runBlocking {
    basicFlowWithException().collect {
        println("BasicFlowCollect emitted value: $it")
    }
}

/*
    This will output 0 1 2
    distinctUntilChanged ignores any duplicates
 */
fun testBasicFlowDistinctCollection() = runBlocking {
    basicFlow().distinctUntilChanged().collect {
        println("BasicFlowDistinctCollect emitted value: $it")
    }
}

/*
    This will output 0 1 2 2
    debounce is ignoring any values emitted faster than the previous one
 */
@OptIn(FlowPreview::class)
fun testBasicFlowDebounceCollection() = runBlocking {
    basicFlow().debounce(80).collect {
        println("BasicFlowDebounceCollect emitted value: $it")
    }
}

/*
    This will output 0 0 1
    take will just take first 3 elements from the flow and finish
 */
fun testBasicFlowTakeCollection() = runBlocking {
    basicFlow().take(3).collect {
        println("BasicFlowDebounceCollect emitted value: $it")
    }
}

/*
    This will output 0 0 1 1 2 2 sum 12
    This is just a simple operator display
 */
fun testBasicFlowGargantuanCollection() = runBlocking {
    val someWeirdSum = basicFlow().onEach {
        delay(200)
        println("Computing $it")
    }.filter {
        it % 2 == 0
    }.map {
        it + 2
    }.reduce { accumulator, value ->
        accumulator + value
    }
    println("SomeGargantuanSum: $someWeirdSum")
}

//  ****
//  Shared/State Flow
//  ****

/*
    replay represents the number of values emitted to new subscribers
 */
val sharedFlow = MutableSharedFlow<Int>(replay = 1)
val stateFlow = MutableStateFlow(69)

/*
    This will output 0 0 1 1 2 2
    Basically this acts like a channel and outputs everything
    Try removing delays though and it will output less values,
    because subscriber thread is too slow to listen to changes.
    SharedFlow is a hot replacement for BroadcastChannel
 */
fun testSharedFlow() = runBlocking {
    sharedFlow.asSharedFlow().onEach {
        println("SharedFlow value: $it")
    }.launchIn(this)

    for (i in 0 until 3) {
        sharedFlow.tryEmit(i)
        delay(100)
        sharedFlow.tryEmit(i)
        delay(100)
    }
}

/*
    This will output 0 1 2
    StateFlow is used to specifically work with states as it will only emit new states.
    StateFlow == SharedFlow with distinctUntilChanged applied.
    This is a perfect replacement for LiveData
 */
fun testStateFlow() = runBlocking {
    stateFlow.asStateFlow().onEach {
        println("StateFlow value: $it")
    }.launchIn(this)

    for (i in 0 until 3) {
        stateFlow.value = i
        delay(100)
        stateFlow.value = i
        delay(100)
    }
}

//  ****
//  Callback/Channel Flow
//  ****

/*
    The following methods represent an attempt to provide some callback values from different threads
    1. Using generic Flow
    2. CallbackFlow
    3. ChannelFlow
 */
@OptIn(DelicateCoroutinesApi::class)
fun dummyFlow(): Flow<Int> = flow {
    GlobalScope.launch {
        emit(1)
        emit(2)
    }
    delay(100)
}

@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
fun callbackFlow(): Flow<Int> = callbackFlow {
    GlobalScope.launch {
        trySend(1)
        trySend(2)
        close()
    }
    delay(100)
    awaitClose { cancel() }
}

@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
fun channelFlow(): Flow<Int> = channelFlow {
    GlobalScope.launch {
        trySend(1)
        trySend(2)
        close()
    }
    delay(100)
    awaitClose { cancel() }
}

/*
    This will crash. Because emission from any other or coroutine is not allowed.
    This can't be used for callbacks.
 */
fun testDummyFlowWithConcurrentEmissions() = runBlocking {
    dummyFlow().collect {
        println("DummyFlow value: $it")
    }
}

/*
    This will work fine and emit 1 2. CallbackFlow is designed to deal specifically with callbacks.
    Great replacement for custom Rx Callback Observables
 */
fun testCallbackFlowWithConcurrentEmissions() = runBlocking {
    callbackFlow().collect {
        println("CallbackFlow value: $it")
    }
}

/*
    This will work fine and emit 1 2, same like callbackFlow
    What's the difference? Try removing awaitClose from callbackFlow and it will crash
    channelFlow - won't. Basically the difference is very minor, callbackFlow is more secure
    awaitClose should be used to close any resources (like observers).
    Also, do not forget to call close() which notifies flow that there is nothing to listen to.
    close() should be called when the final action was performed.
 */
fun testChannelFlowWithConcurrentEmissions() = runBlocking {
    channelFlow().collect {
        println("ChannelFlow value: $it")
    }
}

================================================
FILE: src/main/kotlin/Scopes.kt
================================================
import kotlinx.coroutines.*

/*
    Coroutine scope related examples
 */

fun main() {
    runDefaultScope()
    //runSupervisorScope()
    //testScopeCancellation()
    //testScopeCancellationWithSupervisor()
}

//  ****
//  Task definitions
//  ****

private suspend fun someAsyncTask(iteration: Int): Int {
    delay(3000L / iteration)
    println("[Coroutines] Executed iteration: $iteration")
    if (iteration % 2 == 0) {
        throw IllegalStateException()
    }
    return iteration
}

//  ****
//  Default scope
//  ****

/*
    Example with generic scope.
    All tasks after first exception will be cancelled
 */
private fun runDefaultScope() = runBlocking {
    coroutineScope {
        launch {
            someAsyncTask(1)
        }
        launch {
            someAsyncTask(2)
        }
        launch {
            someAsyncTask(3)
        }
    }
}

//  ****
//  Supervisor scope
//  ****

/*
    Example with supervisor scope.
    All tasks will be executed despite the exceptions
 */
private fun runSupervisorScope() = runBlocking {
    supervisorScope {
        launch {
            someAsyncTask(1)
        }
        launch {
            someAsyncTask(2)
        }
        launch {
            someAsyncTask(3)
        }
    }
}

//  ****
//  Scope cancellation
//  ****

/*
    Example with generic scope.
    Scope will be cancelled after method with iteration 3 will be executed.
    Method with iteration 1 won't be executed
 */
private fun testScopeCancellation() = runBlocking {
    val scope = CoroutineScope(Dispatchers.IO)

    scope.launch {
        someAsyncTask(1)
    }
    scope.launch {
        someAsyncTask(3)
        scope.cancel()
    }
    scope.launch {
        someAsyncTask(5)
    }

    delay(1500)
}

/*
    Deceiving example with supplied supervisor job.
    No tasks will be cancelled. For proper cancellation the job itself should be cancelled.
 */
private fun testScopeCancellationWithSupervisor() = runBlocking {
    val job = SupervisorJob()
    val scope = CoroutineScope(Dispatchers.IO)

    scope.launch(job) {
        someAsyncTask(1)
    }
    scope.launch(job) {
        someAsyncTask(3)
        scope.cancel()
    }
    scope.launch(job) {
        someAsyncTask(5)
    }

    delay(4000)
}

================================================
FILE: src/main/kotlin/shared/exceptions/ApiError.kt
================================================
package shared.exceptions

import kotlinx.serialization.Serializable

@Serializable
data class ApiError(
    override val message: String
) : Error()

================================================
FILE: src/main/kotlin/shared/networking/BaseApiClient.kt
================================================
package shared.networking

interface BaseApiClient

================================================
FILE: src/main/kotlin/shared/networking/BaseApiFactory.kt
================================================
package shared.networking

import io.ktor.client.*
import io.ktor.client.engine.java.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.gson.*
import kotlinx.serialization.json.Json
import shared.exceptions.ApiError

abstract class BaseApiFactory<T : BaseApiClient>(
    private val baseUrl: String,
    private val userAgent: String,
    private val timeout: Int? = null,
    private val logLevel: LogLevel = LogLevel.BODY
) {

    private val json = Json {
        ignoreUnknownKeys = true
    }

    abstract fun createClient(): T

    protected fun createKtorClient(): HttpClient {
        return HttpClient(Java) {

            defaultRequest {
                url {
                    takeFrom(URLBuilder().takeFrom(baseUrl).apply {
                        encodedPath += encodedPath
                    })
                }
                header(HttpHeaders.ContentType, ContentType.Application.Json)
                header(HttpHeaders.UserAgent, userAgent)
            }

            HttpResponseValidator {
                handleResponseException {
                    handleRequestError(it)
                }
            }

            timeout?.let {
                install(HttpTimeout) {
                    requestTimeoutMillis = it.toLong()
                    socketTimeoutMillis = it.toLong()
                    connectTimeoutMillis = it.toLong()
                }
            }

            install(ContentNegotiation) {
                gson {
                    serializeNulls()
                }
            }

            install(Logging) {
                logger = Logger.ANDROID
                level = logLevel
            }
        }
    }

    private suspend fun handleRequestError(requestError: Throwable) {
        val errorToThrow = when (requestError) {
            is ClientRequestException -> {
                val errorString = requestError.response.bodyAsText()
                try {
                    json.decodeFromString(ApiError.serializer(), errorString)
                } catch (e: Exception) {
                    ApiError(message = requestError.message)
                }
            }
            else -> {
                ApiError(message = requestError.message ?: "")
            }
        }
        throw errorToThrow
    }
}
Download .txt
gitextract_zjhzyaig/

├── .github/
│   └── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src/
    └── main/
        └── kotlin/
            ├── Basics.kt
            ├── Channels.kt
            ├── ChannelsVsFlows.kt
            ├── Concurrency.kt
            ├── Flows.kt
            ├── Scopes.kt
            └── shared/
                ├── exceptions/
                │   └── ApiError.kt
                └── networking/
                    ├── BaseApiClient.kt
                    └── BaseApiFactory.kt
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (53K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 645,
    "preview": "# These are supported funding model platforms\n\ngithub: edgar-zigis\npatreon: # Replace with a single Patreon username\nope"
  },
  {
    "path": ".gitignore",
    "chars": 86,
    "preview": "*.iml\n.gradle\n/local.properties\n/.idea\n.DS_Store\n/build\n/captures\n.externalNativeBuild"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 658,
    "preview": "# Coroutine Recipes\nPlayground for Kotlin Coroutines.<br/>\nReady to use ***IntelliJ IDEA*** project with basic explanati"
  },
  {
    "path": "build.gradle",
    "chars": 1102,
    "preview": "plugins {\n    id 'java'\n    id 'org.jetbrains.kotlin.jvm' version '1.7.10'\n    id \"org.jetbrains.kotlin.plugin.serializa"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 200,
    "preview": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributi"
  },
  {
    "path": "gradle.properties",
    "chars": 26,
    "preview": "kotlin.code.style=official"
  },
  {
    "path": "gradlew",
    "chars": 5296,
    "preview": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up"
  },
  {
    "path": "gradlew.bat",
    "chars": 2260,
    "preview": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@r"
  },
  {
    "path": "settings.gradle",
    "chars": 37,
    "preview": "rootProject.name = 'CoroutineRecipes'"
  },
  {
    "path": "src/main/kotlin/Basics.kt",
    "chars": 5070,
    "preview": "import kotlinx.coroutines.*\n\n/*\n    Basic examples on differences between async/launch,\n    cancellations etc.\n */\n\n/*\n "
  },
  {
    "path": "src/main/kotlin/Channels.kt",
    "chars": 3043,
    "preview": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.BroadcastChannel\nimport kotlinx.coroutines.channels.Chann"
  },
  {
    "path": "src/main/kotlin/ChannelsVsFlows.kt",
    "chars": 3266,
    "preview": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.*\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coro"
  },
  {
    "path": "src/main/kotlin/Concurrency.kt",
    "chars": 5264,
    "preview": "\nimport io.reactivex.rxjava3.core.Observable\nimport io.reactivex.rxjava3.core.Single\nimport io.reactivex.rxjava3.schedul"
  },
  {
    "path": "src/main/kotlin/Flows.kt",
    "chars": 6223,
    "preview": "import kotlinx.coroutines.*\nimport kotlinx.coroutines.channels.awaitClose\nimport kotlinx.coroutines.flow.*\n\nfun main() {"
  },
  {
    "path": "src/main/kotlin/Scopes.kt",
    "chars": 2251,
    "preview": "import kotlinx.coroutines.*\n\n/*\n    Coroutine scope related examples\n */\n\nfun main() {\n    runDefaultScope()\n    //runSu"
  },
  {
    "path": "src/main/kotlin/shared/exceptions/ApiError.kt",
    "chars": 149,
    "preview": "package shared.exceptions\n\nimport kotlinx.serialization.Serializable\n\n@Serializable\ndata class ApiError(\n    override va"
  },
  {
    "path": "src/main/kotlin/shared/networking/BaseApiClient.kt",
    "chars": 50,
    "preview": "package shared.networking\n\ninterface BaseApiClient"
  },
  {
    "path": "src/main/kotlin/shared/networking/BaseApiFactory.kt",
    "chars": 2468,
    "preview": "package shared.networking\n\nimport io.ktor.client.*\nimport io.ktor.client.engine.java.*\nimport io.ktor.client.plugins.*\ni"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the edgar-zigis/CoroutineRecipes GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (48.3 KB), approximately 12.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!