Coroutines

What is Coroutines?

Coroutines are used for performing asynchronous task at the background without affecting or blocking the main thread.

Why we use Coroutines for background operation since we have thread and lot more?

Coroutines are light weight thread we can perform asynchronous task on background thread but creating n number of background thread result in out of memory,So we can create single Coroutine and we can perform multiple operation inside it like database access, network operation etc. The Coroutine can communicate with each other and wait.And each Coroutine has its own scope attached to it.

What are the Coroutine builder we have?

async the main purpose is to perform the asynchronous task and wait for the result it return deferred job object and last line of the scope as an return type by using job await we can wait for the result We can perform operation parallely in async.

val job = async {
"Hi"
}
job.await()

runBlocking it block the thread from executing until it completes the Coroutine finishes.The main purpose of runblocking is its used in unit test since we cannt call suspend function from another function so we assign the function with runblocking.

runBlocking {
val job = launch {
"Hi"
}
job.join()
job.cancel()
}

launch it doesnt care about the result it will fire and forgot it return deffered job object by using this we can cancel the job.

val job = launch {
"Hi"
}
job.join()
job.cancel()

WithContext it perform serial operation it execute job one by one

withContext(Dispatchers.IO) { // to run code in Background Thread
// do async work
}

What are Scope of Coroutines?

GlobalScope it will live as long as the application exist.

GlobalScope.launch {
val result = doInBackground(weburl) // runs in background thread without blocking the Main Thread
onPostExecute(result)
}

ViewModelScope it live as long as viewmodel exist

viewModelScope.launch {
val result = doInBackground(weburl) // runs in background thread without blocking the Main Thread
onPostExecute(result)
}

Types Of Dispatcher we have in Coroutines?

Dispatcher.IO to perform long running operation like network calls by default it has 64 thread in it so we can do parallel task since it spend lot time on waiting.

withContext(Dispatchers.IO) {
}

Dispatcher.Main to perofrm ui related operation

withContext(Dispatchers.Main) {
}

Dispatcher.Default to perofrm small operation like json parsing since it have only limited thread.

withContext(Dispatchers.Default) {
}