Introduction
Here's a simple Kotlin Android application code sample that demonstrates the use of Coroutines for asynchronous programming. This example fetches data from a fake API and updates the UI when the data is received using Coroutines.
Make sure to add the necessary dependencies in your app's build.gradle file for Coroutines and Retrofit if you haven't already:
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
Now, let's create the code sample.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
1. Create a data class for the model you want to fetch
data class Post(
val userId: Int,
val id: Int,
val title: String,
val body: String
)
2. Create an interface for your API using Retrofit
import retrofit2.http.GET
interface ApiService {
@GET("posts/1")
suspend fun getPost(): Post
}
3. Create the main activity
class MainActivity : AppCompatActivity() {
private lateinit var textView: TextView
private lateinit var apiService: ApiService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
apiService = retrofit.create(ApiService::class.java)
// Use Coroutines to fetch data asynchronously and update the UI
GlobalScope.launch(Dispatchers.Main) {
try {
val post = apiService.getPost()
textView.text = "Title: ${post.title}\n\nBody: ${post.body}"
} catch (e: Exception) {
textView.text = "Error: ${e.message}"
}
}
}
}
4. Create the layout file activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Loading..."
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
Conclusion
This sample Android app demonstrates the use of Coroutines to make a network request in the background thread and update the UI with the received data when it's available. Make sure to replace the API endpoint and data model with your specific requirements.