Asynchronous Execution with Kotlin Coroutines (under a minute)

Alex Manhooei
1 min readDec 30, 2022

Kotlin coroutines are a powerful tool for writing asynchronous, non-blocking code in a more straightforward and intuitive way. Here’s a fun example of how you might use coroutines in Kotlin to simulate a multi-player game:

import kotlinx.coroutines.*

class Game {
val players = mutableListOf<Player>()

suspend fun start() {
println("Starting game...")
players.forEach { player ->
launch { player.play() }
}
}
}

class Player(val name: String) {
suspend fun play() {
println("$name is playing...")
delay(1000)
println("$name has finished playing!")
}
}

fun main() = runBlocking {
val game = Game()
game.players.add(Player("Alice"))
game.players.add(Player("Bob"))
game.players.add(Player("Charlie"))
game.start()
}

This code creates a Game class that has a list of Player objects, and a start function that launches a coroutine for each player to play the game. The delay function is used to simulate a player taking some time to play their turn.

The output of this code would be something like this:

Starting game...
Alice is playing...
Bob is playing...
Charlie is playing...
Alice has finished playing!
Bob has finished playing!
Charlie has finished playing!

As you can see, coroutines make it easy to write code that performs asynchronous tasks in a sequential and intuitive way, without having to deal with callbacks or other complex async control flows.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alex Manhooei
Alex Manhooei

Written by Alex Manhooei

Staff Software Engineer @ Google. All of my blog posts are my personal opinions and not related to my work at google in any shape or form.

Responses (1)

Write a response

awesome, thanks for sharing