android– 挂起函数’callGetApi’只能从协程或其他挂起函数调用

android– 挂起函数’callGetApi’只能从协程或其他挂起函数调用,第1张

概述我从onCreate调用暂停函数(…)overridefunonCreate(savedInstanceState:Bundle?){......callGetApi()}暂停的功能是:–suspendfuncallGetApi(){....}但错误显示挂起函数’callGetApi’应仅从协程或其他挂起函数调用解决方法:暂停功能只能从协同程

我从onCreate调用暂停函数(…)

overrIDe fun onCreate(savedInstanceState: Bundle?) {    ...    ...    callGetAPI()}

暂停的功能是: –

suspend fun callGetAPI() {....}

但错误显示挂起函数’callGetAPI’应仅从协程或其他挂起函数调用

解决方法:

暂停功能只能从协同程序调用.这意味着您需要使用协同程序构建器,例如发射.例如:

class Activity : AppCompatActivity(), Coroutinescope {    private var job: Job = Job()    overrIDe val coroutineContext: CoroutineContext        get() = dispatchers.Main + job    overrIDe fun onDestroy() {        super.onDestroy()        job.cancel()    }    overrIDe fun onCreate(savedInstanceState: Bundle?) {        launch {            val result =  callGetAPI()            onResult(result) // onResult is called on the main thread        }    }    fun onResult(result: ...) {}}

要在AndroID中使用dispatchers.Main,请在应用程序的build.gradle文件中添加依赖项:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-androID:1.0.1'
总结

以上是内存溢出为你收集整理的android – 挂起函数’callGetApi’只能从协程或其他挂起函数调用全部内容,希望文章能够帮你解决android – 挂起函数’callGetApi’只能从协程或其他挂起函数调用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1111519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存