coroutineScope-happy-case

Here we use coroutineScope with 3 parallel children, coroutineScope will auto wait for them to finish.

Code

package com.glassthought.sandbox

import gt.sandbox.util.output.Out
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.seconds

private val out = Out.standard()
private suspend fun mainImpl(out: Out) {
  coroutineScope {
    foo("msg-1")
  }
}

private suspend fun foo(msg: String) {
  out.actionWithMsg("fooImpl", { fooImpl(msg) })
}

private suspend fun fooImpl(msg: String) {
  coroutineScope {
    launch {
      out.delayNamed(3.seconds, "delayed([${msg}])")
    }
    launch {
      out.delayNamed(2.seconds, "delayed([${msg}])")
    }
    launch {
      out.delayNamed(1.seconds, "delayed([${msg}])")
    }
  }
}


fun main(): Unit = runBlocking {
  out.info("START - ON MAIN")

  try {
    mainImpl(out)
  } catch (e: Exception) {
    out.error("back at MAIN got an exception! of type=[${e::class.simpleName}] with msg=[${e.message}] cause=[${e.cause}]. Exiting with error code 1")

    exitProcess(1)
  }

  out.info("DONE - WITHOUT errors on MAIN")
}

Command to reproduce:

gt.sandbox.checkout.commit e09d077f5c59925b2881 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
Picked up JAVA_TOOL_OPTIONS: -Dkotlinx.coroutines.debug
[INFO][elapsed:   39ms][🥇][①][coroutname:@coroutine#1][tname:main/tid:1] START - ON MAIN
[INFO][elapsed:   54ms][🥇][①][coroutname:@coroutine#1][tname:main/tid:1] [>] Starting action=[fooImpl] 
[INFO][elapsed:   60ms][🥇][⓶][coroutname:@coroutine#2][tname:main/tid:1] Delaying for 3s what_for=[delayed([msg-1])]
[INFO][elapsed:   62ms][🥇][⓷][coroutname:@coroutine#3][tname:main/tid:1] Delaying for 2s what_for=[delayed([msg-1])]
[INFO][elapsed:   62ms][🥇][⓸][coroutname:@coroutine#4][tname:main/tid:1] Delaying for 1s what_for=[delayed([msg-1])]
[INFO][elapsed: 1064ms][🥇][⓸][coroutname:@coroutine#4][tname:main/tid:1] Done delaying for 1s what_for=[delayed([msg-1])]
[INFO][elapsed: 2062ms][🥇][⓷][coroutname:@coroutine#3][tname:main/tid:1] Done delaying for 2s what_for=[delayed([msg-1])]
[INFO][elapsed: 3061ms][🥇][⓶][coroutname:@coroutine#2][tname:main/tid:1] Done delaying for 3s what_for=[delayed([msg-1])]
[INFO][elapsed: 3062ms][🥇][①][coroutname:@coroutine#1][tname:main/tid:1] [<] Finished action=[fooImpl].
[INFO][elapsed: 3062ms][🥇][①][coroutname:@coroutine#1][tname:main/tid:1] DONE - WITHOUT errors on MAIN

Backlinks