Kotlin Cheatsheet 2: Coroutines
Coroutines thread değildir. Daha kolay anlaşılsın diye “Lightweight Thread” olarak tanımlanmıştır . Aslında thread tarafından yürütülen görev parçalarıdır diyebiliriz. Herhangi bir thread x anında bir coroutine’i alıp işletebilir. Ancak bu thread’in ilgili coroutine’i bitene kadar bekleyeceği anlamına gelmez. Bloklayıcı bir bölüme gelindiğinde (suspension point) thread coroutine’i bırakır ve başka bir coroutine’i işletmeye başlayabilir (context switch). Suspend olan görev, işini bitirdiğinde tekrar başka bir thread tarafından işletimine devam edilebilir. Böylelikle thread’ler bloklanmadan verimli bir şekilde kullanılmış olur. Bunu CoroutineDispatcher organize eder. CoroutineDispatcher context switching için suspend keyword’ü ile etiketlenmiş özel function’ları kullanır. Coroutine ile kod örneklerine geçmeden önce suspend functionların iyi anlaşılması gerekmektedir.
CoroutineScope uzerinde çalışırlar. Scope çeşitleri:
- GlobalScope
- RunBlocking
- LifecycleScope
- ViewModelScope
CoroutineScope
Bir task’ı CoroutineScope ile track edebiliriz ve istediğimiz zaman cancel edebiliriz:
class ExampleActivity: AppCompatActivity() { private lateinit var coroutineScope: CoroutineScope private fun coroutineTest() {
coroutineScope = CoroutineScope(Dispatchers.Main)
coroutineScope.launch {
println("loading..")
delay(3000)
println("job is done")
}
} override fun onDestroy() {
super.onDestroy()
if(::coroutineScope.isInitialized && coroutineScope.isActive){
coroutineScope.cancel()
}
}
}
Ayrıca CoroutineScope içindeki sadece bazı taskları cancel edip, bazılarının devam etmesini sağlayabiliriz:
class ExampleActivity: AppCompatActivity() { private lateinit var job1: Job
private lateinit var job2: Job private fun coroutineTest() {
coroutineScope = CoroutineScope(Dispatchers.Main)
job1 = coroutineScope.launch {
println("loading..")
delay(3000)
println("job 1 is done")
}
job2 = coroutineScope.launch {
println("loading..")
delay(3000)
println("job 2 is done")
} } override fun onDestroy() {
super.onDestroy()
if(::job1.isInitialized && job1.isActive){
println("loading..")
job1.cancel()
}
}
}
GlobalScope
GlobalScope is a top level CoroutineScope that is operating as long as the application is alive. We usually use this when we want to launch a running task on application scope so that the task will remains alive until the app killed. Since it’s alive along with application lifetime, GlobalScope is a singleton object. It’s actually same as CoroutineScope but the syntax doesn’t have CoroutineContext on its parameter. By default it will have default CoroutineContext which is Dispatchers.Default except we define CoroutineContext on the launch parameter.
GlobalScope.launch(Dispatchers.Main) {
println("loading..")
delay(3000)
println("job is done")
}We can see the usage example on above snippet code. As we can see unlike CoroutineScope , GlobalScope doesn’t have CoroutineContext constructor. If we want to cancel running task on the GlobalScope, we can simply use methods same as CoroutineScope by using cancel method or cancel the job individually.
LifecycleScope
When we’re using CoroutineScope in Activity/Fragment we have to make sure the running coroutine stop when we destroy the Activity/Fragment to avoid memory leak and resource waste. Therefore we should check and cancel CoroutineScope when the lifecycle owner is about to be destroyed. In this case by using LifecycleScope we don’t have to manually check and cancel the running coroutine before lifecycle owner is destroyed. LifecycleScope tied to the lifecycle so the coroutine lifetime will follow the lifecycle owner lifetime.
Using LifecycleScope we can also use special launch condition:
1. launchWhenCreated will launch coroutine if the lifecycle is at least on create state and gets suspended if it’s on destroy state.
2. launchWhenStarted will launch coroutine if the lifecycle is at least on start state and gets suspended if it’s on stop state.
3. launchWhenResumed will launch coroutine if the lifecycle is at least on resume state and gets suspended if it’s on pause state.
lifecycleScope.launchWhenResumed {
println("loading..")
delay(3000)
println("job is done")
}For instance, code snippet above will be executed if the lifecycle owner (Activity/Fragment) is at least onResumed. If the lifecycle owner is still onCreated or onStarted the coroutine will not be executed. By default LifecycleScope will have Dispatchers.Main as default CoroutineContext.
ViewModelScope
ViewModelScope is similar to LifecycleScope except it happens on ViewModel. Without ViewModelScope usually we want to cancel the coroutine on clear state. But using this ViewModelScope we don’t need to cancel coroutine manually, we can rely onViewModelScope to cancel automatically if the ViewModel is about to be cleared.
viewModelScope.launch {
println("loading..")
delay(3000)
println("job is done")
}Example usage of ViewModelScope can be seen on code snippet above. Same as LifecycleScope, by default ViewModelScope will have Dispatchers.Main as default CoroutineContext.
In conclusion, we can use proper scope for our coroutine as:
1. Use ViewModelScope if you want to run coroutine in ViewModel.
2. Use LifecycleScope if you want to run coroutine in lifecycle owner (Activity/Fragment)
3. Use CoroutineScope if you want to run coroutine for places other than ViewModel and lifecycle owner.
4. Use GlobalScope if you want to run coroutine with application scope running task.
5. Use RunBlocking if you want to run suspend function or library on regular blocking code.
Yeni Bir Coroutine Başlatma
CoroutineScope içinde coroutine başlatmak için coroutine builder denen yapılar kullanılır. Coroutine builder, belirli bir suspend fonksiyonu sarmalayan ve işletilmesini sağlayan fonksiyonlardır. “A bridge from the normal to the suspending world.”
- launch
- runBlocking
- async
- coroutineScope
launch
Çalıştığı thread’i bloklamayan bir builder fonksiyonudur ve Job nesnesi döndürür. Bu fonksiyonu kullanabilmek için CoroutineScope içerisinde olmamız gereklidir. (Ya da GlobalScope uzerinden çağırılabilir. bkz: GlobalScope). Geriye dönüş tipi gerektirmeyen (job hariç, bir değer hesaplayıp döndürmez, sadece job dondurur), arka planda işletilecek operasyonlar için kullanılan builder tipidir. Fire and forget mantığı ile çalışabilecek işler için uygundur. The way launch works is conceptually similar to starting a new thread (thread function). We just start a coroutine, and it will run independently, like a firework that is launched into the air.
fun main() {
printLog("Hello")
val coroutineScope = CoroutineScope(Dispatchers.Default)
coroutineScope.launch {
printLog("from")
delay(3000)
printLog("moon!")
}
printLog("world")
}
// Hello
// world
// from
// (3 secs.)
// moon!--------------------------------------fun main() {
GlobalScope.launch {
delay(1000L)
println("World!")
}
GlobalScope.launch {
delay(1000L)
println("World!")
}
GlobalScope.launch {
delay(1000L)
println("World!")
}
println("Hello,")
Thread.sleep(2000L)
}
// Hello,
// (1 sec)
// World!
// World!
// World!
Not: GlobalScope class, method yada lifecyle’dan bağımsızdır ve bulunduğu thread bitse bile çalışmaya devam eder. Bütün uygulama yaşam döngüsünde çalışır. GlobalScope.launch{}coroutine’i ise işi bitince sonlanır.
runBlocking
Get Mustafa İçmen’s stories in your inbox
Join Medium for free to get updates from this writer.
Yeni bir coroutine başlatır ve tamamlanana kadar çağırıldığı thread’i bloklar. We typically runBlocking to run tests on suspending functions.
Kotlin ekibi coroutine scope içerisinde thread bloklayacak yaklaşımlardan kaçınılmasını önerir. Bu sebeple, runBlocking’in coroutine içerisinde kullanmaktan kaçınmalıyız. Eğer runBlocking kullanılacaksa, hiyerarşide daima en tepede yer almalıdır.
fun main() {
runBlocking {
delay(1000L)
println("World!")
}
runBlocking {
delay(1000L)
println("World!")
}
println("Hello,")
}
// (1 sec)
// World!
// (1 sec)
// World!
// (1 sec)
// World!
// Hello,----------------------------------------------fun main() {
println("Hello")
runBlocking {
println("World")
launch {
println("from")
delay(4000)
println("brother")
}
}
println("moon!")
}
// Hello
// World
// from
// (4 secs)
// brother
// moon!
async
The async coroutine builder is similar to launch, but it is designed to produce a value. It returns some value to the caller. This value needs to be returned by the lambda expression. The async function returns an object of type Deferred<T>, where T is the type of the produced value. Deferred has a suspending method await, which returns this value once it is ready. In the example below, the produced value is 42, and its type is Int, so Deferred<Int> is returned, and await returns 42 of type Int.
fun main() = runBlocking {
val resultDeferred: Deferred<Int> = GlobalScope.async {
delay(1000L)
42
}
// do other stuff...
val result: Int = resultDeferred.await() // (1 sec)
println(result) // 42
// or just
}async can be used to perform an asynchronous task which returns a value. This value in Kotlin terms is a Deferred<T> value.
How the async builder works is very similar to launch, but it has additional support for returning a value. If all launch functions were replaced with async, the code would still work fine. But don't do that! async is about producing a value, so if we don't need a value, we should use launch.
The async builder is often used to parallelize two processes, such as obtaining data from two different places, to combine them together.
fun main() = runBlocking {
val newsDetailsDeferred: Deferred<NewsModel> = async {
newsRepo.getNewsDetails()
}
val similarNewsListDef: Deferred<List<NewsModel>> = async {
newsRepo.getSimilarNewsList()
}
val newsDetails: NewsModel = newsDetailsDeferred.await()
val similarNewsList: List<NewsModel> = similarNewsListDef.await()
view.showNews(newsDetails, similarNewsList)
}---------------------------------
// infact we do not need async for second, because it will already waitfun main() = runBlocking {
val newsDetailsDeferred: Deferred<NewsModel> = async {
newsRepo.getNewsDetails()
}
val similarNewsList = newsRepo.getSimilarNewsList()
val newsDetails: NewsModel = newsDetailsDeferred.await()
view.showNews(newsDetails, similarNewsList)
}
A Note about GlobalScope
GlobalScope kullanmaktan kaçınmalıyız, bunun birkaç sebebi var:
1- If a coroutine is started on GlobalScope, the program will not wait for it. As previously mentioned, coroutines do not block any threads, and nothing prevents the program from ending. This is why, in the below example, an additional delay at the end of runBlocking needs to be called if we want to see "World!" printed. (Main fonksiyonu bittiğinde program akışı da bittiği için GlobalScope.launch()’lar tamamlanamadan bitiriliyor. Ama uygulama devam ediyorsa kapanmaz. Mesela activity içinde bu fonksiyonu cagırırsak normal calısır, cunku uygulama ayakta. Ama uygulamayı ayaga kaldırmadan sadece main fonksiyonunu cagırırsa sadece Hello yazdırır.)
fun main() = runBlocking {
GlobalScope.launch {
delay(1000L)
println("World!")
}
GlobalScope.launch {
delay(2000L)
println("World!")
}
println("Hello,")
delay(3000L)
}
// Hello,But we can get rid of the GlobalScope if we are already in a coroutineScope block; instead, launch can be called on the receiver provided by runBlocking, so with this.launch or simply launch. As a result, launch becomes a child of runBlocking. As parents might recognize, a parental responsibility is to wait for all their children, so runBlocking will suspend until all its children are finished. (Bunu yaparak GlobalScope değil de o an içinde oldugumuz scope’u yani runBlocking’İn olusturdugu scope’u kullanıyoruz. runBlocking de kendi içerisi tamamlana kadar beklediği için tum satırlar yazdırılıyor.)
fun main() = runBlocking {
this.launch { // same as just launch
delay(1000L)
println("World!")
}
launch { // same as this.launch
delay(2000L)
println("World!")
}
println("Hello,")
}
// Hello,
// (1 sec)
// World!
// (1 sec)
// World!2- “Global scope is used to launch top-level coroutines which are operating on the whole application lifetime and are not cancelled prematurely.” GlobalScope creates global coroutines and these coroutines are not children of some specific scope. Hence, it is the developer’s responsibility to keep track of all such global coroutines and destroy them when their job is done. This burden of manually maintaining the lifetime of coroutines can lead to extra effort on the developer’s part. Also, if not handled properly, it can very well lead to memory leaks. Hence, use of GlobalScope should be avoided. However, as we saw, all coroutines must be created within some coroutine scope. Then, what is the recommended way?. As mentioned in Kotlin’s documentation for CoroutineScope — “The best ways to obtain a standalone instance of the scope are CoroutineScope and MainScope factory.”
coroutineScope
coroutineScope is a suspending function that creates a scope for builders. async,launch gibi coroutineBuilder fonksiyonlarını kullanmamız gereken fakat elimizde bir coroutineScope olmadığı durumda kullanılır. Diğer türlü kullanacağımız fonksiyon yada class’a parametre olarak bir coroutineScope objesi vermemiz gerekecekti ve bu iyi bir practice değil.
coroutineScope is a standard function we use when we need a scope inside a suspending function.
Birden fazla data kaynağından veri alıp, bunları merge eden bir senaryo düşünelim. Mesela makaleleri dönen ve user bilgilerini dönen iki servisimiz olsun. Yazacağımız fonksiyon da sadece bu kullanıcı tarafından okunmuş makaleleri dönsün. servislerin birbirini beklemesi için async kullanmamız gerekiyor fakat bunun için bir scope nesnesine ihtiyacımız var ve elimizde yok:
suspend fun getArticlesForUser(
userToken: String?,
): List<ArticleJson> = coroutineScope {
val articles = async { articleRepository.getArticles() }
val user = userService.getUser(userToken)
articles.await()
.filter { canSeeOnList(user, it) }
.map { toArticleJson(it) }
}MainScope
Galiba Dispatcher’ı Dispatchers.Main olan bir coroutineScope olusturuyor, yani main thread’de çalışacak bir coroutineScope oluşturuyor.
val scope1 = CoroutineScope(Dispatchers.IO) // dispatcher zorunlu
val scope2 = MainScope()Dispatchers
Bir coroutine’ in hangi thread üzerinde çalışacağını belirlememizi sağlar. Yani Coroutinelerimizi farklı threadlerde çalıştırmayı sağlar. Yapacağımız işlemin niteliğine göre dispatchersla hangi thread’de olacağını belirtiriz.
Dispatchers.Default : CPU kullanımın yoğun olduğu işlerde kullanılır.Örneğin görüntü işleme gibi ya da çok uzun bir dizinin içinden bir filtreleme yapmak gibi işlerde kullanılır.
Dispatchers.IO : Networking işlemlerinde kullanılır. Örneğin internetten bir veri çekmek veya database ‘den veri almak gibi işlemlerde kullanılır.
Dispatchers.Main : UI ile ilgili yaptığımız işlemler için kullanılır ve Main Thradüzerinde çalışır. Örneğin IO’da yaptığımız bir işi mainle gösterebiliriz. İnternetten veri çekerken IO’yu ,bu veriyi kullanıcıya UI’da gösterirken Main’i kullanabiliriz. Geçiş işlemi ise withContex ile yapılır. (see below)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.Main).launch {
Log.i(
"mstf",
"Main Thread: ${Thread.currentThread().name}"
)
}
CoroutineScope(Dispatchers.IO).launch {
Log.i(
"mstf",
"IO Thread: ${Thread.currentThread().name}"
)
}
CoroutineScope(Dispatchers.Default).launch {
Log.i(
"mstf",
"Default Thread: ${Thread.currentThread().name}"
)
}
}
}// Default Thread: DefaultDispatcher-worker-2
// IO Thread: DefaultDispatcher-worker-1
// Main Thread: main
withContext
Coroutine içinde thread’ler arasında geçiş yapmayı sağlar.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.IO).launch {
val answer = doNetworkCall()
withContext(Dispatchers.Main) {
textview.text = answer }
}
}
private suspend fun doNetworkCall(): String {
delay(2000L)
return "Network Call Answer"
}
}
Biz Dispatchers ile hangi thread’de çalışacağımızı söyledik. İşte yapılan işe göre de hangi Dispatcers öğesiyle çalışacaksak o öğeye geçmemizi sağlayan yapıdır. Bu örnekte internetten veriyi IO’da çektik ve withContext ile Main de UIda gösterdik.
Sources:
https://flexiple.com/android/using-kotlin-coroutine-builders-in-android/
https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc






