Kotlin coroutines on Android Step by Step Basic to advance


Why we need Coroutine?


So, we can say that Coroutines and the threads both are multitasking. But the difference is that threads are managed by the OS and coroutines by the users as it can execute a few lines of function by taking advantage of the cooperation.

It's an optimized framework written over the actual threading by taking advantage of the cooperative nature of functions to make it light and yet powerful. So, we can say that Coroutines are lightweight threads. A lightweight thread means it doesn’t map on the native thread, so it doesn’t require context switching on the processor, so they are faster

 

  • hat exactly Coroutines are?
  • Why there is a need for the solution which Kotlin Coroutines provide?
  • Step by step guide on how to implement the Kotlin Coroutines in Android.
  • What are scopes in Kotlin Coroutines?

What are Coroutines?

Coroutines = Co + Routines

Here, Co means cooperation and Routines means functions.
It means that when functions cooperate with each other, we call it as Coroutines.



1:Create New Project and Lets Start With Coroutines


Open build Gradle Make some changes
add kotlin coroutine dependencies.
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")

plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.10'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
mavenCentral()
jcenter()
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib"
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
}
Main Program 
import kotlinx.coroutines.*
import kotlin.concurrent.thread


fun main()= runBlocking{

println("Main Thread start")

val job: Job= launch {
println("COroutine 2 Starts :")
println("coroutine 2 Ends")
}
job.join()
println("Main Thread ended")
}


Comments

Popular posts from this blog

Click Ads Earn Money 💰 watch ads and earn $5 dollars per Ad with proof👍

All Language Translator App Android Studio Source code by ajjuvirus.inc