Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
64: Building a Simple REST Client with Coroutines
I remember a developer on my team a few years back who was building a small dashboard to track cryptocurrency prices. He used a standard blocking HTTP library and, for a while, everything seemed fine on his high-end workstation. But the moment he deployed it to a low-end Android device, the app just... stopped. The dreaded "Application Not Responding" (ANR) dialog popped up immediately. He was baffled because the API call only took 200ms. The problem was that 200ms of total thread blockage on the UI thread feels like an eternity to the OS. He was trying to handle the "waiting" part by threading manually, which led to a nightmare of nested callbacks that we spent an entire weekend untangling.
This is exactly where Kotlin Coroutines shine. Instead of blocking a thread while we wait for a server in another timezone to respond, we "suspend" the execution. The thread is released to do other work, and when the bytes finally arrive over the wire, the coroutine resumes exactly where it left off. It looks like synchronous, sequential code, but it performs like a highly efficient asynchronous machine.
Wiring up the Ktor Client and Serialization
To build a modern REST client, you'll want to use Ktor. It's the industry standard for Kotlin because it's built from the ground up using coroutines. I generally recommend the CIO (Coroutine-based I/O) engine because it's lightweight and doesn't require a heavy external dependency like Apache or Jetty.
One thing that usually trips people up is the serialization. You can't just throw a JSON string at a Kotlin object; you need a bridge. We use kotlinx.serialization for this. By installing the ContentNegotiation plugin into the Ktor client, we tell the client: "Whenever you see a response with application/json, use this specific library to map it to my data class."
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true // Crucial: prevents crashes if the API adds new fields
prettyPrint = true
})
}
}
Fetching and Parsing the JSON Response
Now let's actually hit an endpoint. For this example, we'll use the PokéAPI—it's public, free, and predictable. Notice that the function we use to fetch the data is marked as suspend. This is the magic word. It tells the compiler that this function can pause its execution without blocking the thread it's running on.
I always suggest creating a dedicated data class for your response. Don't try to parse the whole JSON blob into a Map; it's brittle and a pain to maintain. Define exactly what you need, mark it as @Serializable, and let Ktor handle the rest.
import io.ktor.client.call.*
import io.ktor.client.request.*
import kotlinx.serialization.Serializable
@Serializable
data class Pokemon(
val name: String,
val weight: Int,
val base_experience: Int
)
suspend fun fetchPokemonData(pokemonName: String): Pokemon {
// This call suspends. The thread is free until the response returns.
val response: Pokemon = client.get("https://pokeapi.co/api/v2/pokemon/$pokemonName").body()
return response
}
// Usage inside a coroutine scope
suspend fun main() {
try {
val pikachu = fetchPokemonData("pikachu")
println("Found ${pikachu.name}! Weight: ${pikachu.weight}")
} catch (e: Exception) {
println("Error fetching data: ${e.message}")
} finally {
client.close() // Always close your client to free up resources
}
}
You'll notice I wrapped the call in a try-catch block. In the real world, networks are flaky. DNS fails, servers timeout, and APIs return 404s. If you don't handle these exceptions, your coroutine will fail silently or crash your application. It's a habit you should build early.
📋 Practical Task
GitHub User Profile Fetcher
Your task is to build a small REST client that retrieves public information about a GitHub user. You will need to use the Ktor CIO engine and kotlinx.serialization.
Requirements:
- Create a
@Serializabledata class calledGitHubUserthat captures at least thelogin,id, andpublic_reposfields from the GitHub API. - Implement a
suspendfunction calledfetchGitHubUser(username: String)that makes a GET request tohttps://api.github.com/users/{username}. - In your
mainfunction, launch a coroutine to fetch the profile of a real GitHub user (e.g., "kotlin") and print their public repository count to the console. - Ensure the
HttpClientis configured to ignore unknown keys in the JSON response, as the GitHub API returns a massive amount of data we don't need. - Implement basic error handling to catch and print a message if the user is not found or the network is down.
There are no comments for now.