Suspend function 'callGetApi' should be called only from a coroutine or another suspend function

和自甴很熟 提交于 2020-01-31 04:25:05

问题


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

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

and the suspended function is:-

suspend fun callGetApi() {....}

But the error shows up Suspend function 'callGetApi' should be called only from a coroutine or another suspend function


回答1:


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) {...}
}

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'



回答2:


Looks like the most elegant way to do it as of July 2019, is the one described here:

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super...

        lifecycleScope.launch {
            val result =  callGetApi()
            onResult(result) 
        }
    }
}

Don't forget to add the correponding lib:

implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha02"



回答3:


The above answer worked , but i solved it without inheriting CoroutineScope class by just using .... gradle.build

  dependencies {
      implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
  }

Activity.kt

  import kotlinx.coroutines.GlobalScope
  import kotlinx.coroutines.Dispatchers

  GlobalScope.launch (Dispatchers.Main) { callGetApi() }

Dispatchers.Main is important cause you cannot update the UI in any other thread than main.

But its recommended to inherit CoroutineScope to maintain the lifecycle of the activity and onDestroy of the activity to kill the job



来源:https://stackoverflow.com/questions/53928668/suspend-function-callgetapi-should-be-called-only-from-a-coroutine-or-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!