Language Elements

Data Types

Kotlin Nullable Types

Exctension Functions

Lambda Functions

Object Oriented Kotlin

Data Classes

Coroutines

Collections

Kotlin Example Codes

Kotlin Interview Questions

Multi-threading approach in Android allows to handle tasks on separate thread (or threads) without blocking the Main UI thread. There are common solutions such as Asyntask (currently deprecated), Thread Pool Executor and Rx Java. There is also option to use third party libraries, such as Volley and Retrofit. Coroutines provide a purely Kotlin based lightweight solution, with little risk for memory leaks and many other advantages. Coroutines can run code concurrently, without blocking the main thread. They completely eliminate use of callbacks for switching from one thread to another. They are considered light-weight threads, but more strictly, they are not threads, but just blocks of code used by functions running on one or more predefined threads. Coroutines can be paused, stopped and resumed on the thread they run, eliminating need of unnecessarily keeping thread idle. Coroutines, thus introduced a new way of writing asynchronous, non-blocking code, similar to threads, which can communicate with each other but much light-weight. If needed, spawning thousands of coroutines can be easily done unlike same for threads, with advantages of being much faster and requiring much fewer resources than threads.

Main Coroutine Features

Kotlin's Suspend Function

This kind of function can be started, paused and resumed. It is declared by using suspend keywork beforethe function name. They can be only called from a coroutine or another suspend function. Coroutines are not bound to any specific threads, so they can be suspended in one thread and resumed in another, by use of suspend function. No resources are consumed while a function is suspended. Suspending a function stops any task defined by the function and resumed later in the same or another thread. A thread unlike coroutine can only be blocked.

An example to show how suspend function defined within coroutine for Android. If decalred outside, compiler will throw error.

     
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // Do not call suspend function here.
 
         // Launch coroutine.
        GlobalScope.launch{
        
         // Call suspend function here or from another suspend function only.
       
        } 
 
    }
}

Quiz Questions


  • Coroutines are thought of as light-weight threads. Threads are managed by Operating System. Is that true for coroutines?
  • For a coroutine task running in GlobalScope, can it be destroyed before application is killed?





  • Copyright © by Zafar Yasin. All rights reserved.