使用 dispatch_group_async 从嵌套异步调用中获取通知

Get notification from nested async call with dispatch_group_async

所以我有这样的情况,我想做一些异步的事情,在 Facebook 上 post 状态,并在完成时得到通知 posting。我希望 dispatch_group_async 能完成这项工作,但现在我碰壁了。

这是此刻逻辑的样子。

函数

func saveAndPost() {
    //1. save
    dispatch_group_async(group, queue) { () -> Void in
        print("saving to DB")
        //some func
        print("saved to DB")
    }
    //2. post
    dispatch_group_async(group, queue, { () -> Void in
        print("publishing on FB")
        //some func
        //async request to ACAccount {
            print("access")
            //async performRequestWithHandler{
                print("posted")
                //anwser from request
                }
            }
        }
        print("published on FB")
    })

    dispatch_group_notify(group, queue, { () -> Void in
        print("done")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //go to next view
        })
    })
}

输出

saving to DB
saved to DB
publishing on FB
published on FB
done
post
posted

我的目标是在整个 posting 过程完成时得到通知。也许 dispatch_group_async 这是不可能的,我必须使用 KVO 甚至 PromiseKit?

解决方案

David 让我开始思考,dispatch_group_enter & 'dispatch_group_leave' 正是我所需要的。所以此刻我的逻辑是这样的。

func saveAndPost() {
    //1. save
    dispatch_group_async(group, queue) { () -> Void in
        print("saving to DB")
        //some func
        print("saved to DB")
    }
    //2. post
    dispatch_group_enter(group)
        print("publishing on FB")
        //some func
        //async request to ACAccount {
            print("access")
            //async performRequestWithHandler{
                print("posted")
                //anwser from request
                dispatch_group_leave(group)
                }
            }
        }
        print("published on FB")

    dispatch_group_notify(group, queue, { () -> Void in
        print("done")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //go to next view
        })
    })
}

如您所见,第 2. 部分现已修改。

我在处理异步调用时首选的解决方法:

var asyncGroup = dispatch_group_create()

dispatch_group_enter(asyncGroup)
asyncCall1.start() {


  //end of callback
  dispatch_group_leave(asyncGroup)
}

dispatch_group_enter(asyncGroup)
asyncCall2.start() {

    asyncCall3.start() {

        asyncCall4.start() {

            dispatch_group_leave(asyncGroup)
        }

    }
}

dispatch_group_notify(asyncGroup, dispatch_get_main_queue(), {
    println("done")
})

asyncCall1.start() { ... }asyncCall2.start() { ... } 只是一些伪代码,向您展示它是如何工作的。

每个 dispatch_group_enter 调用都需要通过 dispatch_group_leave 调用来平衡,否则您永远不会进入 dispatch_group_notify 块。