Complete the code to start a network call using Kotlin coroutines.
GlobalScope.launch {
val response = [1]("https://example.com/data.json")
}The fetch function is used here to represent a network call that fetches remote data asynchronously.
Complete the code to convert the network response to a string.
val data = response.[1]()toString() which does not read the content but returns object info.toJson() which is not a standard function.The readText() function reads the response body as a string, which is common after fetching remote data.
Fix the error in the code to make the network call on the main thread safe.
runBlocking {
val result = withContext([1]) {
fetch("https://example.com")
}
}Dispatchers.Main which blocks the UI.Dispatchers.Default which is for CPU-intensive tasks.Network calls should run on Dispatchers.IO to avoid blocking the main thread and keep the app responsive.
Fill both blanks to create a simple function that fetches remote data and returns it as a string.
suspend fun getData(url: String): String {
return withContext([1]) {
val response = fetch(url)
response.[2]()
}
}Dispatchers.Main which blocks UI.toString() which does not read response content.The function uses Dispatchers.IO to run the network call safely and readText() to get the response as a string.
Fill all three blanks to create a coroutine that fetches data and updates the UI safely.
GlobalScope.launch {
val data = withContext([1]) {
fetch("https://api.example.com")
.[2]()
}
withContext([3]) {
textView.text = data
}
}The network call runs on Dispatchers.IO, the response is read as text with readText(), and the UI update runs on Dispatchers.Main to keep the app responsive.