In this blog, I will tell you how you can work with Kotlin coroutines and what is that if you are working with android you have familiar about thread or multithreading concept in java and we can also use thread in Kotlin as well but we generally do not use it directly because we have to do some large task in background and view in UI somehow this can be typical and take a lot of memory and CPU resources of your mobile phone.
what are coroutines?
coroutines can be understood like lightweight thread in android. when you block a thread by thread.sleep method it blocks a whole thread which is not a proper and efficient way In coroutines we can easily do it by delay method and it will not block a thread.
add this line in dependency-
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
code implementation -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CoroutineScope(IO).launch { | |
try { | |
//do your work in background | |
withContext(Main) { | |
//do your work in main thread when background task complete | |
} | |
}catch (e:HttpException){ | |
Log.v("Exception",e.toString()) | |
} | |
} |
Download Project- Click me
0 Comments