Why do we need Kotlin Coroutine?
- When you have multiple background tasks that need to be performed, using separate threads can be an option, but creating too many threads can be expensive in terms of resource usage and can lead to performance issues.
- For example, you could launch a coroutine to upload a file, another coroutine to perform a network operation, and a third coroutine to download files, all within the same background thread.
- MultiThreading in Kotlin:
Coroutine:
- Unlike threads, for coroutines the application by default does not wait to finish its execution.
- By default, the code inside a coroutine will execute sequentially.
GlobalScope.launch() {
println("Hi")
delay(1000)
}
}
// use $Thread.currentThread().name to get the current thread.
// Globalscope is a companion object
- Thread.sleep() vs delay()
- GlobalScope:
Suspending Functions:
- A function with suspend modifier and this functions are only allowed to be called inside another suspending function or a courotine scope.
- When a function is marked with
suspend, it means that it can be paused and resumed at a later time without blocking the thread that it is running on.
Coroutine Builders:
RunBlocking:
- It is a function that allows you to block the current thread until a coroutine has completed its execution.
- GlobalScope.launch will not block the thread in which it is operating while the Runblocking does that.
- The actual prupose of runBlocking comes when you want to test your code which contains suspend functions.
fun myFirstTest() = runBlocking{
myOwnSuspendFunction()
}