挂起函数"callGetApi"只能从协程或其他挂起函数中调用 [英] Suspend function 'callGetApi' should be called only from a coroutine or another suspend function

查看:505
本文介绍了挂起函数"callGetApi"只能从协程或其他挂起函数中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从onCreate(...)调用暂停的函数

I am calling suspended function from onCreate(...)

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    ...
    callGetApi()
}

并且暂停的功能是:-

suspend fun callGetApi() {....}

但错误显示仅应从协程或其他暂停函数调用暂停函数'callGetApi'

推荐答案

仅应从协程调用挂起函数.这意味着您需要使用协程生成器,例如launch.例如:

Suspend function should be called only from coroutine. That means you need to use a coroutine builder, e.g. launch. For example:

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?) {
        super.onCreate(savedInstanceState)
        launch {
            val result =  callGetApi()
            onResult(result) // onResult is called on the main thread
        }
    }

    suspend fun callGetApi(): String {...}

    fun onResult(result: String) {...}
}

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

To use Dispatchers.Main in Android add dependency to the app's build.gradle file:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'

这篇关于挂起函数"callGetApi"只能从协程或其他挂起函数中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆