複数の非同期処理を同時に流して、全部が完了したタイミングで次の処理を開始したいとき、iOSではDispatchGroupを使って手軽にできるが、同じことをAndroidで実現する方法を調べてこれを見つけた↓
元ネタ: Android how to group async tasks together like in iOS
それを微妙に改変した↓
class DispatchGroup {
private var count = 0
private var runnable: (() -> Unit)? = null
init {
count = 0
}
@Synchronized
fun enter() {
count++
}
@Synchronized
fun leave() {
count--
notifyGroup()
}
fun notify(r: () -> Unit) {
runnable = r
notifyGroup()
}
private fun notifyGroup() {
if (count <= 0) {
runnable?.invoke()
}
}
}
使うときは
val dispatchGroup = DispatchGroup()
dispatchGroup.enter()
functionA(completion = {
print("functionAが完了")
dispatchGroup.leave()
})
dispatchGroup.enter()
functionB(completion = {
print("functionBが完了")
dispatchGroup.leave()
})
dispatchGroup.enter()
functionC(completion = {
print("functionCが完了")
dispatchGroup.leave()
})
dispatchGroup.notify {
print("全部の処理が完了")
}