In the simplest terms, a coroutine is a way to write asynchronous code sequentially. It is a lightweight thread used in applications. Coroutines are defined as "lightweight threads" by the Kotlin team. They are the types of jobs that actual threads can complete.
Coroutines were added to Kotlin in version 1.3 and are based on well-known notions from other languages. Kotlin coroutines are a new type of concurrency that may be utilized on Android to simplify async mobile applications.
There are three types of coroutines
- Launch
- Async
- RunBlocking
1. Launch: Launch is used to fire and forget coroutine, Here’s a simple example
We are launching a new coroutine using Goblaescope.launch inside of coroutine . delay is one second then print message.
2. Asyn: It is part of coroutines . it starts a new coroutine and returns a Deferred<T > .which is a non-blocking future .Here’s example
This computation is suspend function computerResult which delays for one second then return 42.
3.RunBlocking: RunBlocking is a bridge between the coroutine world and the coroutine world. It is a way to start the top main coroutine.
Happy coding!