Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to launch a coroutine in the main scope.
Android Kotlin
GlobalScope.[1] { println("Hello from coroutine") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using runBlocking blocks the thread, which is not desired here.
Using delay is a suspending function, not a coroutine builder.
✗ Incorrect
The launch function starts a new coroutine without blocking the current thread.
2fill in blank
mediumComplete the code to suspend a coroutine for 1 second.
Android Kotlin
suspend fun waitOneSecond() {
[1](1000L)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Thread.sleep blocks the thread, which defeats the purpose of coroutines.
✗ Incorrect
The delay function suspends the coroutine without blocking the thread.
3fill in blank
hardFix the error in the coroutine builder to return a deferred result.
Android Kotlin
val deferred = GlobalScope.[1] { 42 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using launch returns Job, not a result.
Using delay is not a builder.
✗ Incorrect
The async builder returns a Deferred, which can hold a result.
4fill in blank
hardFill both blanks to create a coroutine scope and launch a coroutine.
Android Kotlin
val scope = CoroutineScope([1] + Job()) scope.[2] { println("Running in scope") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using async when no result is needed.
Using Dispatchers.IO for UI work.
✗ Incorrect
Use Dispatchers.Main for UI thread and launch to start coroutine.
5fill in blank
hardFill the two blanks to create a suspending function that fetches data asynchronously.
Android Kotlin
suspend fun fetchData(): String {
return withContext([1]) {
val data = apiCall()
if (data.isNotEmpty()) data else [2]
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Dispatchers.Main for network calls.
Using println instead of returning data.
✗ Incorrect
withContext(Dispatchers.IO) switches to IO thread for network call.
The if expression returns the data or "No data" if empty.