22

I am using Kotlin and right now android studio suggest me to add

This is a delicate API and its use requires care. Make sure you fully read and understand documentation of the declaration that is marked as a delicate API.

and when I click to

add @DelicateCoroutinesApi annotation to function

it added @DelicateCoroutinesApi something like this

@DelicateCoroutinesApi
fun getAmount(activity: LoginActivity, user:FirebaseUser){
      mFireStore.collection(Constants.AMOUNT).document(user.uid).get().
            addOnSuccessListener { d ->
                 activity.amountGetSuccess( d, user)
            }
 }

when I use coroutine it suggests me let's see another example

@DelicateCoroutinesApi
 private fun playsound() {

   GlobalScope.launch {
        withTimeout(10L) {
            // play sound
   val  mPlayerPress = MediaPlayer.create(this, R.raw.button_press)
            mPlayerPress.start()
        }
    }

my question is why this @DelicateCoroutinesApi what is the work of @DelicateCoroutinesApi

James Z
  • 12,209
  • 10
  • 24
  • 44
Adarsh Dhakad
  • 347
  • 1
  • 3
  • 10

1 Answers1

24

@DelicateCoroutinesApi annotation is required for certain API uses, If you look at the documentation it states

Marks declarations in the coroutines that are delicatethey have limited use-case and shall be used with care in general code. Any use of a delicate declaration has to be carefully reviewed to make sure it is properly used and does not create problems like memory and resource leaks. Carefully read documentation of any declaration marked as DelicateCoroutinesApi.

Use of GlobalScope requires this annotation, because GlobalScope falls in the catetory 'have limited use-case and shall be used with care'.

This is because kotlin coroutines follow a principle of structured concurrency which means that new coroutines can be only launched in a specific CoroutineScope which delimits the lifetime of the coroutine. for example if you start a coroutine with viewModelScope, then this coroutine will be cancelled as soon as ViewModel is destroyed.

but GlobalScope on the other hand creates global couroutines, their lifetime is the responsibility of programmer and if for some reason(network delay etc) these global coroutines can't complete then they keep running and consuming system resources, this behaviour along with other issues, can cause memory leaks hence the DelicateCoroutinesApi.

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
  • 1
    So how do we destroy the `GlobalScope` coroutine then? – Balaji Sep 03 '22 at 07:02
  • @Balaji `GlobalScope` is destroyed when your app is destroyed so if you want to destroy your coroutine-specific scope you can create your Owen CoroutineScope and then cancel it and suggest using `viewModelScope` and `lifecycleScope` – yousef Nov 12 '22 at 14:24