Saturday 9 July 2022

What are coroutines in Kotlin?

Coroutines in Kotlin are like threads, but not quite like threads. They allow asynchronous computing. 

Their functionality is brought to bear from the library kotlinx.coroutines, developed by JetBrains

Put simply, a coroutine in Kotlin is a unit of suspendable computation Such a computation may be suspended in one thread, then reawoken in another thread. The keyword launch is used to launch a coroutine, and delay suspends the coroutine for a period of time, but does not hog the underlying thread.

Android Jetpack

Jetpack is a collection of useful Android libraries.  A typical Android app will have multiple layers: a UI layer, an (optional) domain layer and a back-end ("data") layer. A candidate for code in the domain layer would be complex business logic that is used across multiple ViewModels.

LiveData and ViewModel are examples of JetPack components. LiveData is interesting, it follows the Observer pattern and notifies Observer objects when the underlying data changes. This way you don't need to write update code in the UI every time the underlying application data changes. Observers have a void return onChanged method that gets called every time data is changed.