Parallel api call threading using CoroutineWorker in kotlin android

A CoroutineWorker in Android is a part of the Android WorkManager library that allows you to perform background tasks in a structured and reliable way, leveraging Kotlin's coroutines for concurrency. You can use CoroutineWorker to execute tasks that require network calls, database operations, or any other asynchronous work while ensuring compatibility with Android's background execution constraints.

Here's a step-by-step guide on how to make parallel API calls in a CoroutineWorker in Android using Kotlin, you can use Kotlin's async and await functions from the kotlinx.coroutines library. Here's a step-by-step guide on how to do this:

  1. Add the kotlinx.coroutines library to your app's dependencies and ensure you have the WorkManager dependency added to your app's build.gradle file. If it's not already there, you can do this by adding the following line to your app's build.gradle file:

build.gradle (app level)
 
dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0" implementation("androidx.work:work-runtime-ktx:2.7.1") }
  1. Create a CoroutineWorker class that will perform parallel API calls. Extend CoroutineWorker and override the doWork method.
kotlin code snippet
import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope class MyWorker( context: Context, params: WorkerParameters ) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = coroutineScope { try { // Create a list of async tasks for parallel API calls val apiCall1 = async { performApiCall1() } val apiCall2 = async { performApiCall2() } // Wait for all async tasks to complete val results = awaitAll(apiCall1, apiCall2) // Handle the results as needed val apiCall1Result = results[0] val apiCall2Result = results[1] // Process the results and do other work here // Return the success result Result.success() } catch (e: Exception) { // Handle errors here and return a failure result Result.failure() } } private suspend fun performApiCall1(): SomeResult { // Implement your API call logic here // Return the result of the API call } private suspend fun performApiCall2(): SomeResult { // Implement your second API call logic here // Return the result of the API call } }

In the code above:

  • We create two asynchronous tasks (apiCall1 and apiCall2) using the async function, each representing an API call.
  • We use awaitAll to wait for all async tasks to complete.
  • You can handle the API call results as needed and return a success or failure result.
  1. Finally, schedule the MyWorker to run using WorkManager as you normally would with any other Worker class.
kotlin code snippet:
val workRequest = OneTimeWorkRequest.Builder(MyWorker::class.java).build() WorkManager.getInstance(context).enqueue(workRequest)

This example demonstrates how to make parallel API calls within a CoroutineWorker. You can customize it according to your specific API call requirements and error handling.

Migrate Android gradle from Groovy Scripts to KTS (Kotlin script)

This section will guide your step-by-step to convert or migrate your Android project's Gradle build script from Groovy script to Kotlin DSL

 When we create a project in Android (Arctic Fox 2020.3.1), We get the default Gradle Script setup for us which has 3 gradle file written in Groovy script

These 3 Gradle files are:
    1. The settings.gradle
    2. The root project’s build.gradle
    2. The app module’s build.gradle

Convert the settings.gradle file
1. Rename settings.gradle to settings.gradle.kts

You can do so by selecting the settings.gradle file, then go to Refactor
→ Rename File.

Then, just convert it to settings.gradle.kts. 

2. Fix the file syntax for “include”

You just need to change

include ':app'
to

include("app")

settings.gradle example file in groovy script:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url 'https://maven.google.com'
        }
        maven {
            url 'https://maven.fpregistry.io/releases'
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }
}
rootProject.name = "Project name text"
include ':app'

'include ':news'
include ':events'
include ':home'
include ':profile'
include ':common'

example file becomes settings.gradle.kts in Kotlin script:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven(url = "https://jitpack.io")
        maven(url = "https://maven.google.com")
        maven(url = "https://maven.fpregistry.io/releases")    
        maven(url = "https://oss.sonatype.org/content/repositories/snapshots/")    
    }
}
rootProject.name = "Be better"
include("app")
include("news")
include("events")
include("home")
include("profile")
include("common")

Popular Posts