swift - 有没有办法对函数调用进行排队?
问题描述
为了在结帐过程中与后端通信,我具有异步功能:
create():在后端创建购物车。当用户转到结帐页面时调用。
update():在后端编辑购物车。当用户编辑购物车时调用。
confirm():在后端确认购买。当用户下订单时调用。
update()取决于create()的响应,confirm()取决于create() / update()的响应
用户可以在另一个功能未完成时调用一个功能,例如在转到结帐页面后不久编辑购物车。由于依赖关系,这会导致问题。
我目前已经通过使用 bools processing、shouldUpdate和shouldConfirm半解决了这个问题。
有没有办法通过使用队列来实现下一个函数调用等待前一个函数调用完成?
var processing = false // Set true when a function is executing
var shouldUpdate = false // Set true when user edits cart
var shouldConfirm = false // Set true when user taps "Purchase"
var checkoutID = ""
func create() {
processing = true
APIClient.sharedClient.createShoppingCart() {
(checkoutID, error) in
...
processing = false // Finished with network call
if shouldUpdate { // if edit was done while create() is running
update()
shouldUpdate = false
}
if shouldConfirm { // if user tapped "Purchase" while create() is running
confirm()
}
}
}
func update() { // Called from view controller or create()
if processing {return}
processing = true
APIClient.sharedClient.updateShoppingCart(forCheckoutID: checkoutID) {
(error) in
...
processing = false // Finished with network call
if shouldConfirm { // if user tapped "Purchase" while update() is running
confirm()
}
}
}
func confirm() { // Called from view controller or create()/update()
if processing {return}
APIClient.sharedClient.confirmPurchase(forCheckoutID: checkoutID) {
(error) in
...
/// Finish order process
}
}
解决方案
您可以使用调度组
let apiDispatchGroup = DispatchGroup()
func asyncCall1() {
apiDispatchGroup.enter()
print("Entered")
DispatchQueue.main.asyncAfter(deadline: .now()+3) {
/// After 3 Second it will notify main Queue
print("Task 1 Performmed")
/// Let's notify
apiDispatchGroup.leave()
}
apiDispatchGroup.notify(queue: .main) {
/// Perform task 2
asyncCall2()
}
}
func asyncCall2() {
print("Task 2")
}
推荐阅读
- ios - Appstore Connect Testflight 提供旧版本,即使我上传了新版本
- c# - 如何创建此动画过渡?
- php - 如何从另一个查询结果运行一个查询。(单级传销倒数)
- nlp - IBM NL Classifier 和 NLU 定制模型分类有什么区别?
- c - C 为什么scanf返回错误的输出
- r - 从需要使用 R 登录的站点中抓取信息(可能使用 API)
- oracle - Need output in below format in oracle. I have tried with lag function it worked if we have only 2 rows in table
- haskell - Haskell 和理解列表
- r - 根据两个数据集中的匹配条件创建变量
- python - 从 Github 安装包不起作用(可能是 .egg 文件有问题)