我不是Kotlin协程的新手,我正尝试使用启动从oncreate调用暂停函数。但是代码无法执行。
launch {
callSomeApi()
}
suspend fun callSomeApi() {
withContext(Dispatcher.IO) {
//perform network call
}
}
表示暂停功能只能从协程或其他暂停功能中调用。虽然我从启动就称呼它。请让我知道我做错了什么? please see attached image
答案 0 :(得分:1)
您必须这样做:
CoroutineScope(Dispatchers.Main).launch {
someSuspendFunction()
}
通过这种方式,您可以分配一个CoroutineScope来管理协程。 请记住,您必须完全导入协程依赖项:
// coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'