我正在从 onCreate(...) 调用挂起函数
override fun onCreate(savedInstanceState: Bundle?) {
...
...
callGetApi()
}
暂停的功能是:-
suspend fun callGetApi() {....}
但错误出现了挂起函数“callGetApi”只能从协程或另一个挂起函数调用
挂起函数只能从协程中调用。
这意味着调用一个suspend
您需要使用的功能协程构建器 https://kt.academy/article/cc-builders, e.g. launch
, async
or runBlocking
(建议仅在单元测试中使用)。例如:
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
在 Android 中添加对应用程序的依赖build.gradle
file:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
The 最近的方法将使用扩展属性ViewModel
and Activity
/Fragment
:
-
In ViewModel https://developer.android.com/topic/libraries/architecture/viewmodel我们可以用viewModelScope https://developer.android.com/topic/libraries/architecture/coroutines#viewmodelscope启动协程:
viewModelScope.launch { ... }
它附加到生命周期Activity/Fragment
并在销毁时取消启动的协程。
- 类似的
Activity/Fragment
我们可以使用以下扩展属性来启动协程:lifecycleScope.launch {} https://developer.android.google.cn/reference/kotlin/androidx/lifecycle/package-summary#lifecyclescope, lifecycle.coroutineScope.launch {} https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope, viewLifecycleOwner.lifecycleScope.launch {} https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope(适用于Fragments
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)