挂起函数只能在协程体内调用
Suspension functions can be called only within coroutine body
我检查了其他问题,但其中 none 似乎解决了我的问题。
我的 HomeViewModel
中有两个 suspend fun
,我在 HomeFragment
中调用它们(带有微调器文本参数)。
HomeViewModel
中的两个挂起函数:
suspend fun tagger(spinner: Spinner){
withContext(Dispatchers.IO){
val vocab: String = inputVocab.value!!
var tagger = Tagger(
spinner.getSelectedItem().toString() + ".tagger"
)
val sentence = tagger.tagString(java.lang.String.valueOf(vocab))
tagAll(sentence)
}
}
suspend fun tagAll(vocab: String){
withContext(Dispatchers.IO){
if (inputVocab.value == null) {
statusMessage.value = Event("Please enter sentence")
}
else {
insert(Vocab(0, vocab))
inputVocab.value = null
}
}
}
这就是我在 HomeFragment
:
中的称呼
GlobalScope.launch (Dispatchers.IO) {
button.setOnClickListener {
homeViewModel.tagger(binding.spinner)
}
}
在 tagger
我收到错误消息“只能在协程体内调用暂停函数”。但它已经在全球范围内。我怎样才能避免这个问题?
But it's already inside a global scope.
对 button.onSetClickListener()
的调用是在从 CoroutineScope
启动的协同程序中进行的。但是,您传递给 onSetClickListener()
的 lambda 表达式是一个单独的对象,映射到一个单独的 onClick()
函数,并且 that 函数调用不是该对象的一部分协程。
您需要将其更改为:
button.setOnClickListener {
GlobalScope.launch (Dispatchers.IO) {
homeViewModel.tagger(binding.spinner)
}
}
顺便说一句,您不妨回顾一下 Google's best practices for coroutines in Android, particularly "The ViewModel
should create coroutines"。
我检查了其他问题,但其中 none 似乎解决了我的问题。
我的 HomeViewModel
中有两个 suspend fun
,我在 HomeFragment
中调用它们(带有微调器文本参数)。
HomeViewModel
中的两个挂起函数:
suspend fun tagger(spinner: Spinner){
withContext(Dispatchers.IO){
val vocab: String = inputVocab.value!!
var tagger = Tagger(
spinner.getSelectedItem().toString() + ".tagger"
)
val sentence = tagger.tagString(java.lang.String.valueOf(vocab))
tagAll(sentence)
}
}
suspend fun tagAll(vocab: String){
withContext(Dispatchers.IO){
if (inputVocab.value == null) {
statusMessage.value = Event("Please enter sentence")
}
else {
insert(Vocab(0, vocab))
inputVocab.value = null
}
}
}
这就是我在 HomeFragment
:
GlobalScope.launch (Dispatchers.IO) {
button.setOnClickListener {
homeViewModel.tagger(binding.spinner)
}
}
在 tagger
我收到错误消息“只能在协程体内调用暂停函数”。但它已经在全球范围内。我怎样才能避免这个问题?
But it's already inside a global scope.
对 button.onSetClickListener()
的调用是在从 CoroutineScope
启动的协同程序中进行的。但是,您传递给 onSetClickListener()
的 lambda 表达式是一个单独的对象,映射到一个单独的 onClick()
函数,并且 that 函数调用不是该对象的一部分协程。
您需要将其更改为:
button.setOnClickListener {
GlobalScope.launch (Dispatchers.IO) {
homeViewModel.tagger(binding.spinner)
}
}
顺便说一句,您不妨回顾一下 Google's best practices for coroutines in Android, particularly "The ViewModel
should create coroutines"。