小编Jou*_*man的帖子

挂起函数只能在协程体内调用

我检查了其他问题,但似乎没有一个问题能解决我的问题。我的 my 中有两个suspend funs HomeViewModel,我在 my 中调用它们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
           }
       }
    }
Run Code Online (Sandbox Code Playgroud)

这就是我在中称呼它们的方式HomeFragment

GlobalScope.launch (Dispatchers.IO) {
        button.setOnClickListener {
            homeViewModel.tagger(binding.spinner)
        }
    }
Run Code Online (Sandbox Code Playgroud)

我收到tagger错误“只能在协程体内调用暂停函数”。但它已经在全球范围内了。我怎样才能避免这个问题?

android kotlin kotlin-coroutines

6
推荐指数
1
解决办法
8461
查看次数

标签 统计

android ×1

kotlin ×1

kotlin-coroutines ×1