Quick introduction of Android Coroutine to iOS developers

·

2 min read

In one sentence Coroutine is similar as Structure Concurrency (async/await) in Swift & GCD/OperationQueues in Objective-C.

In Simple definition

Coroutines are a concurrency feature introduced in Kotlin, they are used to perform long-running operations without blocking the main thread, which can cause the app to become unresponsive.

These are lightweight threads that can be used to perform tasks in the background.

The main advantage of coroutines is that they simplify asynchronous programming by allowing developers to write asynchronous code that looks like synchronous code. With coroutines, developers can use simple, sequential code to express complex asynchronous behaviour. (Sounds familiar like async/await in swift).

Here is the most basic example

// Define a coroutine
fun fetchData() = CoroutineScope(Dispatchers.IO).launch {
    // Perform network call on background thread
    val response = apiService.getData()
    // Update UI on main thread
    withContext(Dispatchers.Main) {
        updateUI(response)
    }
}

In the above example, fetchData() is a coroutine that performs a network call on a background thread using the Dispatchers.IO dispatcher. Once the network call is complete, the updateUI() method is called on the main thread using the Dispatchers.Main dispatcher.


What is CoroutineScope?

To create Coroutine, we use an interface known as CoroutineScope, this interface provides a way to manage coroutines & represents a context for running coroutines, including a set of rules and constraints that define how coroutines should behave.

This interface provides several methods for launching coroutines, including launch(), async(), and runBlocking(). These methods provide a way to start a new coroutine that runs concurrently with others.

It also provides a couple of methods to cancel the running coroutines, such as cancel(), cancelChildren() , withTimeout(), & some more


Hope the iOS devs are now introduced to Coroutines.

You can reach out to me via Linked In or https://nasirmomin.web.app