📖 Scenario: Imagine you are making a simple program that waits for a task to finish, but you don't want to wait forever. You want to stop waiting if it takes too long.
🎯 Goal: You will build a Kotlin program that uses withTimeout to stop waiting after a set time.
📋 What You'll Learn
Create a suspend function that simulates a long task
Set a timeout duration using withTimeout
Run the task inside withTimeout
Handle the timeout exception and print a message
💡 Why This Matters
🌍 Real World
Timeouts are useful when waiting for slow tasks like network calls or user input, so your program doesn't freeze or wait forever.
💼 Career
Many jobs require handling timeouts to keep apps responsive and avoid crashes, especially in mobile and backend development.
Progress0 / 4 steps
1
Create a suspend function to simulate a long task
Write a suspend function called longTask that waits for 3000 milliseconds using delay(3000).
Kotlin
Hint
Use suspend fun to create a function that can pause. Use delay(3000) to wait 3 seconds.
2
Set a timeout duration using withTimeout
Create a val timeoutMillis and set it to 2000L to represent 2000 milliseconds timeout.
Kotlin
Hint
Use val timeoutMillis = 2000L to set the timeout to 2 seconds.
3
Run the task inside withTimeout
Write a suspend function called runWithTimeout that uses withTimeout(timeoutMillis) to run longTask().
Kotlin
Hint
Use withTimeout(timeoutMillis) { longTask() } inside the new suspend function.
4
Handle timeout exception and print result
Write a main function that calls runBlocking and inside it calls runWithTimeout(). Catch TimeoutCancellationException and print "Timeout happened!". If no timeout, print "Task completed".
Kotlin
Hint
Use try { runWithTimeout() } and catch (e: TimeoutCancellationException) to print the timeout message.
Practice
(1/5)
1. What does the Kotlin function withTimeout do?
easy
A. It cancels all running coroutines immediately.
B. It repeats a block of code until a timeout occurs.
C. It stops a block of code if it runs longer than the specified time.
D. It delays the execution of a block for a fixed time.
Solution
Step 1: Understand the purpose of withTimeout
withTimeout is designed to stop a block of code if it exceeds a given time limit.
Step 2: Compare options with the definition
Only "It stops a block of code if it runs longer than the specified time." correctly describes this behavior. Other options describe different coroutine behaviors.
Final Answer:
It stops a block of code if it runs longer than the specified time. -> Option C
A. TimeoutCancellationException is thrown because delay exceeds timeout.
B. Syntax error: withTimeout requires a try-catch block.
C. No error; code runs and prints "Done" after 200ms.
D. Delay function cannot be used inside withTimeout.
Solution
Step 1: Understand withTimeout behavior with delay
The delay of 200ms exceeds the 100ms timeout, causing a TimeoutCancellationException.
Step 2: Check error handling
No try-catch is present, so exception will be thrown and program will crash.
Final Answer:
TimeoutCancellationException is thrown because delay exceeds timeout. -> Option A
Quick Check:
Delay longer than timeout causes exception [OK]
Hint: Delay longer than timeout causes exception unless caught [OK]
Common Mistakes:
Assuming code waits full delay then prints
Thinking try-catch is mandatory syntax
Believing delay can't be used inside withTimeout
5. You want to run a network request that should timeout after 500ms. Which Kotlin code correctly uses withTimeout to achieve this and handle timeout gracefully?