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

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

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

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

3条回答
  •  时光取名叫无心
    2020-12-03 01:21

    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"
    

提交回复
热议问题