Uses of Coroutines in Android. Know how to use Coroutines for… | by Vipul Saluja | Feb, 2022

Know how to use Coroutines for long-running tasks and main thread safety

Vipul Saluja
Photo by Marc Reichelt on Unsplash
  1. Main Safety

Long running tasks are those that take too much time to execute and we have to wait for them, these tasks can be any network request that we make to fetch data from the webserver or it could be reading of any file in the device.

class NotesViewModel:ViewModel(){
fun fetchNotes(){
get(“someurl”){
result->{
showNotes(result)
}
}
}
}

Use of coroutines in long-running tasks

This operation can also be done with the help of coroutines. But the main difference here will be that it will not block the main thread whereas it works on the concept of suspending and resume.

class NotesViewModel : ViewModel() {
suspend fun fetchNotes() {
var result = get(“ someurl ”){
showNotes(result)
}
}

suspend fun get(url: String) {
/**/
}
}

In Kotlin these suspend functions are safe to call from the main thread as they do not block the main thread. Besides these tasks, there are several functions in android that we cannot perform on the main thread due to their slow behavior like JSON Parsing, reading, and writing data to or from the database so all these tasks can be done using the suspend function.

  1. Dispatchers.IO
  2. Dispatchers.Default

Dispatchers.Main

As the name indicates this runs on the main thread and is used for updating the UI of the app. Suspend functions can be called from here.

Dispatchers.IO

It runs in the background thread and is used mostly for network-related heavy tasks.

Dispatchers.Default

It works the background thread and is used mostly for CPU-intensive work like the parsing of the JSON or accessing any list.

class NotesViewModel : ViewModel() {
suspend fun fetchNotes() {
//Dispatchers.Main
var result = get(“ someurl ”){
//Dispatchers.Main
showNotes(result)
}
}

//Dispatchers.IO
suspend fun get(url: String) {
/**/
}
}

Performance of withContext

withContext is as fast as callbacks or RxJava for providing main safety. It’s even possible to optimize withContext calls beyond what’s possible with callbacks in some situations.

As we have seen that what problem we can solve through coroutines. Coroutines is an old concept that becomes popular recently due to their ability to make code that interacts with networks much simpler.

  1. Performing main safety means that your code will not block the main thread and will stay simple.

Kotlin coroutines on Android

Leave a Comment