Skip to content

Instantly share code, notes, and snippets.

@jlorenzen
Last active April 20, 2022 16:18
Show Gist options
  • Save jlorenzen/fd59f692bc5e6e710490f36498d016ac to your computer and use it in GitHub Desktop.
Save jlorenzen/fd59f692bc5e6e710490f36498d016ac to your computer and use it in GitHub Desktop.
kotlin-coroutines
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.time.LocalDateTime
fun printWithDatePrefix(msg: String) =
println("${LocalDateTime.now()} : $msg")
suspend fun fetchItems(): List<String> {
printWithDatePrefix("starting fetch")
delay(5_000L)
printWithDatePrefix("finished fetch")
return listOf("a1", "a2", "a3")
}
suspend fun submitItem(item: String) {
printWithDatePrefix("starting submit: $item")
delay(2_000L)
printWithDatePrefix("finished submit: $item")
}
runBlocking {
printWithDatePrefix("starting")
val items = fetchItems()
items.forEach {
launch {
submitItem(it)
}
}
printWithDatePrefix("after launching jobs")
}
printWithDatePrefix("finished")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment