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

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

问题描述

我正在从 onCreate(...) 调用挂起的函数

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

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

和暂停的功能是:-

suspend fun callGetApi() {....}

但是出现了错误挂起函数'callGetApi'应该只从协程或其他挂起函数调用

推荐答案

挂起函数只能从协程中调用.这意味着您需要使用协程构建器,例如启动.例如:

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天全站免登陆