Home > Mobile >  kotlin error - suspension functions can be called only within coroutine body
kotlin error - suspension functions can be called only within coroutine body

Time:10-06

I'm brand new in Kotlin, basically I'm following a guide to create this app but was done with older Kotlin version.

My problem is here in my java/MainActivity.kt file

This is the function I'm trying to call

    private suspend fun getTokenAsync(): String {
        return getToken()
    }

and here is the caller

private suspend fun handleLoadWebView() {
        
        //some code here.....

        var token: String

        runBlocking{
            val resp = async { getTokenAsync() }
            token = resp.await()
            val jsonResp = JSONObject(token)
            loadWebView(exampleActivity, jsonResp.getString("access_token"), subdomain, content, options)
        }
    }

but getting the error in this line val resp = async { getTokenAsync() }

CodePudding user response:

You really messed things up a bit here.

First of all, both functions are suspendable, so you don't need runBlocking() there. In fact, you should never (?) use runBlocking() inside a suspend function. Second, running async() just to immediately await() on it doesn't make too much sense. This is almost the same as invoking getTokenAsync() directly. Also, the name of getTokenAsync() may be misleading as suspend functions are actually invoked synchronously.

Your whole handleLoadWebView() could be replaced with simple:

private suspend fun handleLoadWebView() {
    val jsonResp = JSONObject(getTokenAsync())
    loadWebView(exampleActivity, jsonResp.getString("access_token"), subdomain, content, options)
}

However, there may be more things going on here, so I don't say this is a fully working example.

  • Related