LoginSignup
1
0

More than 3 years have passed since last update.

AndroidでiOSのDispatchGroupと同じことをしたい。

Last updated at Posted at 2019-10-28

複数の非同期処理を同時に流して、全部が完了したタイミングで次の処理を開始したいとき、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("全部の処理が完了")
        }
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0