Skip to main content

Boost Performance: Kotlin Coroutines with Didit API

Discover how Kotlin Coroutines can supercharge your Didit API integrations, enabling non-blocking, high-performance identity verification workflows.

Boost Performance: Kotlin Coroutines with Didit API

Contents

In this guide

Jump to the part you need.

Asynchronous EfficiencyKotlin Coroutines enable non-blocking operations, crucial for UI responsiveness and high-volume API calls, ensuring a smooth user experience even during complex identity verification.

Simplified ConcurrencyCoroutines abstract away complex threading models, allowing developers to write asynchronous code that reads like synchronous code, reducing boilerplate and potential errors in Didit API integrations.

Resource OptimizationBy suspending instead of blocking, Coroutines use fewer threads and consume less memory, making your applications more scalable and cost-effective, especially when handling numerous Didit identity checks.

Enhanced User ExperienceFaster response times and a fluid UI, directly resulting from efficient Didit API calls with Coroutines, translate into higher conversion rates and improved user satisfaction for identity verification processes.

The Need for Speed: Why Asynchronous Processing Matters for Identity

In today's fast-paced digital world, user expectations for instant gratification are higher than ever. When it comes to critical processes like identity verification, any delay can lead to user frustration, abandonment, and ultimately, lost business. Didit's identity platform offers a robust suite of tools for verification, biometrics, fraud detection, and compliance, all accessible via its powerful API. To fully leverage the speed and efficiency of the Didit API, particularly in applications requiring real-time responses or processing a high volume of requests, asynchronous programming is not just an option—it's a necessity.

Traditional blocking I/O operations can halt the execution of your application, leading to unresponsive UIs or inefficient server-side processing. For example, imagine a mobile app where a user initiates an ID verification. If the API call blocks the main thread, the app freezes until the response is received. This is where Kotlin Coroutines shine. They provide a lightweight solution for asynchronous programming, allowing your application to perform long-running tasks, like network requests to the Didit API, without blocking the main thread or consuming excessive resources.

Introducing Kotlin Coroutines: A Lightweight Approach to Concurrency

Kotlin Coroutines are a powerful feature that simplifies asynchronous programming and makes concurrent code easier to write and understand. Unlike traditional threads, which are managed by the operating system and come with significant overhead, coroutines are user-level, lightweight threads managed by the Kotlin runtime. This means you can launch thousands of coroutines with minimal performance impact, making them ideal for I/O-bound operations like API calls.

The core concept behind coroutines is suspension. Instead of blocking a thread while waiting for a result (e.g., from a Didit API response), a coroutine can suspend its execution and allow the underlying thread to do other work. Once the result is ready, the coroutine resumes from where it left off. This non-blocking nature is fundamental to building highly responsive and scalable applications.

Let's look at a basic example of how you might integrate the Didit API using a suspend function:

import kotlinx.coroutines.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST

// Assume Didit API interface
interface DiditApiService {
    @POST("identity/verify")
    suspend fun verifyIdentity(@Body request: IdentityVerificationRequest): IdentityVerificationResponse
}

// Data classes for request and response (simplified)
data class IdentityVerificationRequest(val documentId: String, val selfieImage: String)
data class IdentityVerificationResponse(val status: String, val score: Double)

object DiditApiClient {
    private const val BASE_URL = "https://api.didit.me/v1/"

    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val service: DiditApiService = retrofit.create(DiditApiService::class.java)
}

suspend fun performDiditVerification(docId: String, selfie: String): IdentityVerificationResponse {
    val request = IdentityVerificationRequest(docId, selfie)
    return DiditApiClient.service.verifyIdentity(request)
}

fun main() = runBlocking {
    // Example usage in a non-blocking way
    val job = launch {
        try {
            val response = performDiditVerification("doc123", "base64SelfieData")
            println("Verification Status: ${response.status}, Score: ${response.score}")
        } catch (e: Exception) {
            println("Verification failed: ${e.message}")
        }
    }
    job.join() // Wait for the coroutine to complete
}

In this example, performDiditVerification is a suspend function, meaning it can be paused and resumed. When verifyIdentity (a network call) is made, the coroutine suspends, freeing up the thread. Once the Didit API responds, the coroutine resumes and processes the result. This is a fundamental shift from callback-based or reactive programming models, offering cleaner, more readable code.

Practical Implementation Strategies for Didit API with Coroutines

Integrating Didit's API with Kotlin Coroutines involves several best practices to ensure optimal performance and maintainability:

1. Structured Concurrency with Coroutine Scopes

Always launch coroutines within a CoroutineScope. This ensures that all coroutines launched within that scope are tracked and can be cancelled when the scope is no longer needed (e.g., when a ViewModel is cleared in Android, or a request is completed on a server). This prevents resource leaks and ensures proper lifecycle management.

class MyViewModel(private val diditRepository: DiditRepository) : ViewModel() {
    private val _verificationResult = MutableLiveData<String>()
    val verificationResult: LiveData<String> = _verificationResult

    fun startIdentityVerification(docId: String, selfie: String) {
        viewModelScope.launch {
            try {
                val response = diditRepository.verifyIdentity(docId, selfie)
                _verificationResult.value = "Status: ${response.status}, Score: ${response.score}"
            } catch (e: Exception) {
                _verificationResult.value = "Error: ${e.message}"
            }
        }
    }
}
// In Android, viewModelScope is provided by lifecycle-viewmodel-ktx

2. Dispatchers for Thread Management

Coroutines need to know which thread pool to run on. Kotlin provides built-in Dispatchers:

  • Dispatchers.Main: For UI updates (e.g., Android's main thread).
  • Dispatchers.IO: Optimized for network and disk I/O operations (perfect for Didit API calls).
  • Dispatchers.Default: For CPU-intensive work.

By explicitly specifying the dispatcher, you ensure that blocking operations don't interfere with the UI thread and that I/O operations are handled efficiently.

class DiditRepository(private val diditApiService: DiditApiService) {
    suspend fun verifyIdentity(docId: String, selfie: String): IdentityVerificationResponse {
        return withContext(Dispatchers.IO) {
            diditApiService.verifyIdentity(IdentityVerificationRequest(docId, selfie))
        }
    }
}

3. Error Handling

Coroutines simplify error handling with standard try-catch blocks, making your code more robust. Use try-catch around your suspend function calls to gracefully handle network errors, API failures, or other exceptions that might occur during Didit API interactions.

4. Concurrent Didit API Calls

When your application needs to make multiple independent Didit API calls simultaneously (e.g., an ID document check, a liveness detection, and an AML screening), Coroutines provide elegant solutions using async and await.

suspend fun performMultiStepVerification(docId: String, selfie: String, userId: String): String = coroutineScope {
    val idVerificationDeferred = async(Dispatchers.IO) {
        DiditApiClient.service.verifyIdentity(IdentityVerificationRequest(docId, selfie)) // Simplified
    }
    val livenessCheckDeferred = async(Dispatchers.IO) {
        DiditApiClient.service.checkLiveness(LivenessRequest(selfie)) // Hypothetical Liveness API
    }
    val amlScreeningDeferred = async(Dispatchers.IO) {
        DiditApiClient.service.performAmlScreening(AmlRequest(userId)) // Hypothetical AML API
    }

    val idResult = idVerificationDeferred.await()
    val livenessResult = livenessCheckDeferred.await()
    val amlResult = amlScreeningDeferred.await()

    if (idResult.status == "APPROVED" && livenessResult.isLive && amlResult.isClean) {
        "Full verification successful!"
    } else {
        "Verification failed: ID: ${idResult.status}, Liveness: ${livenessResult.isLive}, AML: ${amlResult.isClean}"
    }
}

This approach allows the three API calls to execute concurrently, significantly reducing the total time required for a multi-step verification process compared to executing them sequentially.

How Didit Helps

Didit's platform is designed for high-performance and scalability, offering a single API to orchestrate complex identity workflows. By integrating Didit with Kotlin Coroutines, you can unlock its full potential:

  • Faster Onboarding: Reduce the time users spend waiting for verification results, leading to higher conversion rates for new sign-ups.
  • Responsive Applications: Ensure your mobile or web applications remain fluid and responsive, even during intensive identity checks involving multiple Didit modules like ID verification, liveness detection, and AML screening.
  • Efficient Resource Usage: Handle a large volume of concurrent verification requests without overwhelming your server resources, thanks to the lightweight nature of coroutines.
  • Simplified Development: Write cleaner, more maintainable asynchronous code, allowing your team to focus on building features rather than wrestling with complex threading issues.
  • Global Scalability: Didit's global infrastructure combined with the scalable nature of Coroutines means your identity verification solution can grow with your user base, no matter where they are.

Ready to Get Started?

Embracing Kotlin Coroutines for your Didit API integrations is a strategic move towards building more performant, scalable, and user-friendly applications. By simplifying asynchronous programming, coroutines allow you to deliver a seamless identity verification experience, which is paramount in today's digital landscape.

Explore Didit's comprehensive identity platform and see how easily you can integrate its powerful features into your Kotlin applications. The future of identity verification is fast, secure, and non-blocking.

Ready to enhance your application's performance and provide a superior user experience? Learn more about Didit and start building today!

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

Questions

Blog questions

Who writes the Didit blog?
The Didit team. Guides reviewed by Alberto Rosas, co-founder and CEO, carry his byline. The rest are published as Didit.
Which topics does the blog cover?
Eight topics: ID verification, business verification (KYB), AML, sanctions and compliance, fraud prevention, transaction monitoring and crypto, country guides, agents and developers, and product updates.
Is the blog available in my language?
Yes, in 15 languages: English, Spanish, French, German, Brazilian and European Portuguese, Catalan, Russian, Arabic, Chinese, Japanese, Hindi, Indonesian, Korean and Swahili. Not every post is translated, so each language shows the posts it has.
Where do I find product updates?
In the changelog at /changelog/ and under the Product updates topic.
Are these posts legal advice?
No. Regulation posts explain rules; your legal team decides how they apply.
How do I find posts on one topic?
Open one of the eight topics, or search the blog.
Are posts dated?
Yes. Every post shows when it was published and when it was last updated.
Do posts link to the docs?
Developer posts link to the matching page on docs.didit.me and to the API reference.
Is the blog the same as the docs?
No. The blog explains rules, markets and product changes for a general reader, while docs.didit.me holds the integration guides and the API reference. Developer posts link the matching docs page and the API reference they describe.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.