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

Jou*_*man 6 android kotlin kotlin-coroutines

我检查了其他问题,但似乎没有一个问题能解决我的问题。我的 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错误“只能在协程体内调用暂停函数”。但它已经在全球范围内了。我怎样才能避免这个问题?

Com*_*are 10

但它已经在全球范围内了。

对的调用button.onSetClickListener()是在从 启动的协程中进行的CoroutineScope。但是,您传递到的 lambda 表达式onSetClickListener()是一个单独的对象,映射到一个单独的onClick()函数,并且函数调用不是该协程的一部分。

您需要将其更改为:

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

顺便说一句,您可能希望查看Google 关于 Android 中协程的最佳实践,特别是ViewModel应该创建协程”