Android Networking: Beyond the Basics

Sep 8 2022 · Kotlin 1.7.10, Android 12, Android Studio Chipmunk

Part 2: Retrofit With Kotlin Coroutines

09. Use Kotlin Coroutines to Shorten API Calls

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 08. Introduction Next episode: 10. Include Built-in Retrofit Support for Coroutines

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Just to show how easy implementing coroutines is, and how the code is more understandable than using callbacks, or some other mechanism, you’ll change the deleteTask API call, to rely on Coroutines. Let’s see how to do just that! :]

Demo

To start implementing coroutines, you need to add their dependency to the project. Open app level build.gradle. Then add the following dependencies to the project:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
fun deleteTask(taskId: String): Result<String> {
}
suspend fun deleteTask(taskId: String) = withContext(Dispatchers.IO) {

}
suspend fun deleteTask(taskId: String) = withContext(Dispatchers.IO) {
  try {
    val data = apiService.deleteNote(taskId).execute().body()

    if (data?.message == null) {
      Failure(NullPointerException("No response!"))
    } else {
      Success(data.message)
    }
  } catch (error: Throwable) {
    Failure(error)
  }
}
viewLifecycleOwner.lifecycleScope.launch {

}
val result = remoteApi.deleteTask(taskId)

if (result is Success) {
  taskOptionSelectedListener?.onTaskDeleted(taskId)
}
dismissAllowingStateLoss()