【发布时间】:2018-02-07 07:00:00
【问题描述】:
我有一个 Android 服务,它在服务器在线时启动并与服务器同步不同类型的数据。 我是 Kotlin 协程的新手,我正在尝试完成以下工作:
fun syncData{
//Job1 make retrofit call to server
//Job2 make retrofit call to server after job1 is done.
//Job3 make retrofit call to server after job2 is done and so on.
//After all jobs are done I'll stop service.
}
我正在关注这个帖子: Kotlin Coroutines the right way in Android
这让我想到了这个解决方案:
fun syncData() = async(CommonPool){
try{
val sync1 = async(CommonPool){
job1.sync()
}
val sync2 = async(CommonPool){
job2.sync()
}
val sync3 = async(CommonPool){
job3.sync()
}
val sync4 = async(CommonPool){
job4.sync()
}
job1.await()
job2.await()
job3.await()
job4.await()
}catch (e: Exception){
}finally {
stopSelf()
}
}
但是当我在 logcat 上获得改造的日志时,每次调用都是混合的。来自 job3 的调用在 job1 之前,以此类推。 如何在管道中执行它们?我有点迷失在 Kotlin 的协程中,所以我不知道具体如何实现。
【问题讨论】:
-
您能否澄清一下
job1、job2等变量的类型以及它们上的sync()函数到底在做什么? -
问题解决了吗?
-
是的,有点。我仍然使用协程,因为我最终不需要等待每个结果。所以效果很好。但主要问题是我列出的每个作业都是一个改造调用,这是一个异步调用,但我想等待每个调用结束,这就是为什么我认为 async await 可以为我提供解决方案。
标签: kotlin async-await android-service kotlin-coroutines