async/await | Coroutines | Kotlin

Tony Trejo
2 min readMar 9, 2023
async/await | Coroutines | Kotlin

async/await | Coroutines

  • async/await simplifies asynchronous code, making it easier to read and maintain.
  • Coroutines execute long-running tasks without blocking the main thread or freezing the UI.
  • async launches a coroutine and returns a Deferred object; await retrieves the result.
  • The exceptions can be handled with try/catch or onFailure to prevent crashes and unexpected behavior.

Scratch.kts file

import com.hacoga.asyncawait.Post
import kotlinx.coroutines.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import java.net.URL
import kotlin.coroutines.CoroutineContext

requestPosts() // Output: Posts count: 100

// Request posts
fun requestPosts() = runBlocking {
val sample = Sample(coroutineContext)
val posts = sample.fetchAsync().await()
println("Posts count: " + posts.count())
}

class Sample(override val coroutineContext: CoroutineContext)
: CoroutineScope {
fun fetchAsync() = async { fetchPosts() }
// Fetch posts
private fun fetchPosts(): Array<Post> {
val url = "https://jsonplaceholder.typicode.com/posts"
val json = URL(url).readText()
return Json.decodeFromString<Array<Post>>(json)
}
}

MainActivity.kts file

package com.hacoga.asyncawait

import android.os.Bundle
import android.provider.ContactsContract.CommonDataKinds.Website.URL
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import com.hacoga.asyncawait.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.*
import kotlinx.serialization.Serializable
import java.net.URL

@Serializable
data class Post(val userId: Int,
val id: Int,
val title: String,
val body: String)

class MainActivity : AppCompatActivity() {

private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

setSupportActionBar(binding.toolbar)

val navController = findNavController(R.id.nav_host_fragment_content_main)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)

binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}

}

Hey there! Are you a mobile developer looking for some fun and informative content? Look no further than my channel! With a focus on all things mobile development, my content is sure to keep you engaged and inspired. So why not join my community of mobile enthusiasts today? Hit that follow button and let’s dive into the exciting world of mobile together!

--

--