我目前正在学习协程,需要你的帮助:)
我如何强制等待,直到retrofit 初始化?
private lateinit var retrofit: Retrofit
init {
val time = measureTimeMillis {
launch {
val httpClient = createOkHttpClient(...)
val gson = createGson()
retrofit = createRetrofit(httpClient.await(), gson.await())}
}
logger.debug("Init time: $time")
}
private fun <T> createService(class: Class<T>) = retrofit.create(_class)
使用 runBlocking 它可以工作,但我真的不想使用它...
提前致谢!
最佳答案
How I can force to wait until my object retrofit has initialized?
Coroutines 在这里帮不了你。如果在迁移到协程之前,您可以在 Retrofit 初始化时阻塞主 UI 线程,那么就这样吧,不要涉及协程。
如果您有一个在后台执行的异步任务,那么无论 late init 过去的后果是什么,它们也将保留在协程中。
协程给你的唯一优势是干净的编程模型:
launch {
val httpClient = createOkHttpClient(...)
val gson = createGson()
retrofit = createRetrofit(httpClient.await(), gson.await())
... take the actions that depend on retrofit ...
}
一旦 httpClient
和 gson
初始化,您的协程将在 UI 线程上恢复。然后它可以采取行动使您的应用程序初始化继续进行。与此同时, Activity 的 onCreate
已完成,因此您必须将那里所有依赖于 Retrofit 的内容移动到 launch
block 中。
关于android - Kotlin Coroutines 等到完成 init block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52928753/