我正在使用 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 delicate — they 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/