Kotlin’s coroutines are used for asynchronous programming which allows a program to be executed without waiting for the completion of previous tasks. This is done by suspending a coroutine at a safe point until the required resource becomes available. Primary use cases for Kotlin’s coroutines are:
1. Networking calls: By using coroutines, we can make HTTP requests in a non-blocking way, without blocking the main thread.
2. File I/O: By using coroutines, we can read and write files in a non-blocking way, without blocking the main thread.
3. Concurrency: By using coroutines, we can perform concurrent tasks in a safe manner, without worrying about synchronization issues.
4. User Interface: By using coroutines, we can update the UI without blocking the main thread.
Kotlin’s coroutines can be created using two different builders: ‘launch‘ and ‘async‘.
1. ‘launch‘ creates a coroutine that runs in the background without returning a result. It is used when we want to perform some operation in the background without waiting for the result. The ‘launch‘ function is called with a lambda function that contains the code to be executed in the background.
For example:
fun main() {
GlobalScope.launch {
println("This code runs in the background")
}
println("This code runs on the main thread")
}
In this example, the ‘launch‘ function is used to execute the ‘println()‘ statement in the background, while the ‘println()‘ statement outside of the ‘launch‘ function executes on the main thread.
2. ‘async‘ creates a coroutine that runs in the background and returns a ‘Deferred‘ object, which is a promise to return a result in the future. It is used when we want to perform some operation in the background and get a result.
For example:
fun main() {
val deferredResult = GlobalScope.async {
"This code runs in the background and returns a result"
}
println("This code runs on the main thread")
runBlocking {
println(deferredResult.await())
}
}
In this example, the ‘async‘ function is used to execute the lambda expression in the background and returns a ‘Deferred‘ object that holds the result of the lambda expression. The ‘await()‘ function is used to wait for the completion of the deferred result and then print it. The ‘runBlocking‘ function is used to block the main thread until the background operation completes.
In conclusion, ‘launch‘ is used to perform some operation in the background without waiting for the result, while ‘async‘ is used to perform some operation in the background and get a result.