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

前端 未结 3 2357
[愿得一人]
[愿得一人] 2020-12-03 00:50

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

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

3条回答
  •  無奈伤痛
    2020-12-03 01:42

    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

提交回复
热议问题