Asynchronous execution in Kotlin and Swift

Ivan Fytsyk
3 min readOct 28, 2018

--

Hello. Today we are going to explain and compare concurrency models in Kotlin and Swift. This knowledge would be useful for persons who want to learn both Android and iOS frameworks or already develop on both platforms. More information you could get from my book.

Basic terms which we are going to operate are Thread, Operation, Queue. Thread — low-level abstraction that uses multi-core CPU to execute some calculations at the same time. On single-core CPU parallel execution is emulated by frequently switching between operations. Nowadays Threads are not commonly used directly either in Kotlin or Swift so we won’t consider working with them in this article. Creating new threads and managing them requires a lot of system resources, so in modern development, we usually use some predefined pool of threads and work with Operations and Queues. Operation — it’s just a block of code, usually represented as closure or some OOP abstractions (DispatchItem in Swift and Task in Kotlin). Queue — it’s a FIFO collection of Operations, each of them could be taken and executed on different threads.

Adding a new Operation to the Queue is possible in 2 ways: sync and async. Sync way means that current operation (from which we start a new one) will be suspended till started operation ends and if we start new operation asynchronously, our current operation will continue execution without suspending.

Fewer words, more code. Let’s look at how these basic entities are implemented in Kotlin and Swift. We’ll use Android Studio Kotlin REPL and XCode Playground to run our code samples.

Kotlin sample:

import kotlinx.coroutines.experimental.*

runBlocking {
GlobalScope.async { // Kotlin sample
delay(1000L) // 1 second suspending
println("async call")
}
delay(2000L)
}

Swift sample:

DispatchQueue.global().async { //Swift sample  sleep(1) //emulates heavy operation, delay 1 second  print("async call")}

Let’s explain what is happening here. First of all look at part runBlocking{..} in Kotlin sample. It’s a blocking function that allows us to see the result of async execution before REPL main thread finished. It’s just a construction to help us run our code samples. XCode Playground is running without similar construction. Next what we are interested in are GlobalScope and DispatchQueue.global(). These entities encapsulate “predefined working threads” and operations queues which I mentioned before. In most cases, these are enough to run our code asynchronously. For more specific cases we can create our custom queues.

After the heavy operation completes in the background we usually sent a result of this execution to UI thread. Look how it’s done in Kotlin:

import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.Main

val job = GlobalScope.async {
delay(1000L) // 1 second suspending
println("async call")
GlobalScope.async(context = Dispatchers.Unconfined) { //replace it to Dispatchers.Main in real Android application
println(" called in UI thread")
}
}
runBlocking {
job.join()
}

and Swift:

DispatchQueue.global().async {  sleep(1) // 1 second suspending  print("async call")  DispatchQueue.main.async {    print(" called in UI thread")  }}

Here we blocked UI thread using job.join() to wait for asynchronous block execution. It’s just replacement of delay() which we used in the previous example.

So for executing code block in UI thread, we’re using predefined main queues with constructions: GlobalScope.async(context = Dispatchers.Unconfined) {} in Kotlin and DispatchQueue.main.async {} in Swift.

That was the easiest case of concurrency in mobile development: heavy calculation/data fetching in the background and sending the result to UI thread. In the next chapters, we’ll consider what can we do with operations and queues, create our own queues and review how to solve concurrency problems: deadlocks and race conditionals.

If you are interested in learning both Android and iOS development, you can check my new book from here. In this book, I explore the basic knowledge of Mobile development, UI creating and Architecture. After reading this book you’ll be able to develop on iOS as well as on Android.

Make the world professional!

And read my book.

--

--