Complete the code to launch a coroutine in the main scope.
GlobalScope.[1] { println("Hello from coroutine") }
The launch function starts a new coroutine without blocking the current thread.
Complete the code to suspend a coroutine for 1 second.
suspend fun waitOneSecond() {
[1](1000L)
}The delay function suspends the coroutine without blocking the thread.
Fix the error in the coroutine builder to return a deferred result.
val deferred = GlobalScope.[1] { 42 }
The async builder returns a Deferred, which can hold a result.
Fill both blanks to create a coroutine scope and launch a coroutine.
val scope = CoroutineScope([1] + Job()) scope.[2] { println("Running in scope") }
Use Dispatchers.Main for UI thread and launch to start coroutine.
Fill the two blanks to create a suspending function that fetches data asynchronously.
suspend fun fetchData(): String {
return withContext([1]) {
val data = apiCall()
if (data.isNotEmpty()) data else [2]
}
}withContext(Dispatchers.IO) switches to IO thread for network call.
The if expression returns the data or "No data" if empty.
