android - 为什么使用 GlobalScope 需要 @DelicateCoroutinesApi

标签 android android-studio kotlin kotlin-coroutines

我正在使用 Kotlin,现在 android studio 建议我
添加

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.


当我点击
add @DelicateCoroutinesApi annotation to function
它添加了@DelicateCoroutinesApi像这样的东西
@DelicateCoroutinesApi
fun getAmount(activity: LoginActivity, user:FirebaseUser){
      mFireStore.collection(Constants.AMOUNT).document(user.uid).get().
            addOnSuccessListener { d ->
                 activity.amountGetSuccess( d, user)
            }
 }
当我使用协程时,它建议我让我们看看另一个例子
@DelicateCoroutinesApi
 private fun playsound() {

   GlobalScope.launch {
        withTimeout(10L) {
            // play sound
   val  mPlayerPress = MediaPlayer.create(this, R.raw.button_press)
            mPlayerPress.start()
        }
    }
我的问题是为什么这个@DelicateCoroutinesApi
@DelicateCoroutinesApi 的工作是什么

最佳答案

@DelicateCoroutinesApi某些 API 使用需要注释,如果您查看 documentation它指出

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.


使用 GlobalScope需要这个注解,因为 GlobalScope属于“have limited use-case and shall be used with care”类别'。
这是因为 kotlin 协程遵循 structured concurrency 的原则。这意味着新的协程只能在特定的 CoroutineScope 中启动它限定了协程的生命周期。例如,如果您使用 viewModelScope 启动协程, 那么这个协程会在 ViewModel 被取消被摧毁。
但是 GlobalScope另一方面,创建全局协同程序,它们的生命周期是程序员的责任,如果由于某种原因(网络延迟等)这些全局协同程序无法完成,那么它们会继续运行并消耗系统资源,这种行为 along with other issues , 可能导致内存泄漏,因此 DelicateCoroutinesApi .

关于android - 为什么使用 GlobalScope 需要 @DelicateCoroutinesApi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68599452/

相关文章:

android - 日期和时间选择器,什么是最好(和简单)的解决方案?

android camera2 qrscanner 二维码扫描器

android - 将顶部栏添加到底部导航 View 项

java - 在 MainActivity 的 fragment 中显示 EditText 的值

android - Android Studio 渲染问题

ListView 行中的 Android 图库

java - 在另一个 Fragment 中创建 ArFragment 对象

android - kapt 发生异常 : java. lang.OutOfMemoryError: 超出 GC 开销限制

java - 改变油漆的颜色会改变所有圆圈的颜色

Android 低功耗蓝牙摩托罗拉 API 配对