DispatchGroup 逻辑工作流

时间:2021-04-10 04:15:12

标签: ios swift multithreading grand-central-dispatch

我正在尝试按如下方式实现 DispatchGroup,但如果第一个调用返回 true,那么第二个调用返回 false,那么总体结果将返回 false

但是,如果第一个调用返回 false,然后第二个调用返回 true,那么总体结果将返回 false,这不是我所期望的。

如果任何调用返回 false,我想返回 false。我该如何处理这个问题?

 func storeInformation(id: String?, _ completion: @escaping (Bool) -> ()) {
    guard
      let id =  id
    else {
      completion(false)
      return
    }
    let dispatchGroup = DispatchGroup()
    var groupResult: Bool = false
    dispatchGroup.enter()
    storeFeatures { success in
      if success {
        groupResult = true
      } else {
        groupResult = false
      }
      dispatchGroup.leave()
    }
    
    dispatchGroup.enter()
    storeClasses { success in
      if success {
        groupResult = true
      } else {
        groupResult = false
      }
      dispatchGroup.leave()
    }
    dispatchGroup.notify(queue: .main) {
      completion(groupResult)
    }
  }

  private func storeClasses(_ completion: @escaping(Bool) -> Void) {
    postClasses { (error) in
      if let _ = error {
        completion(false)
      } else {
        completion(true)
      }
    }
  }

  private func storeFeatures(_ completion: @escaping(Bool) -> Void) {
    postFeatures { (error) in
      if let _ = error {
        completion(false)
      } else {
        completion(true)
      }
    }
  }

2 个答案:

答案 0 :(得分:2)

如果我们查看您的 storeClassesstoreFeatures,我们会发现它们不是真正返回布尔值的操作;它们本质上是尝试发布一些可能会失败的东西。因此,您真正想知道的不是返回 truefalse 的东西,而是它是否失败。这就是你真正的意思 - 在编程中,说出你的意思总是更好。

使用Combine 框架,我们可以以难以置信的简洁方式表达这种行为。当我们有多个异步操作要同时执行时,这就是合并。如果其中一个失败,整个合并失败。换句话说,您想做的事情实际上是自动的!

想象一下,例如,我们通过将您的发布操作包装在类型为 <Void,Error> 的延迟期货中来表达您的发布操作。假设我们有方法 storeClassesFuturestoreFeaturesFuture 产生这些 Futures。那么你只需要说:

Publishers.Merge(storeClassesFuture(), storeFeaturesFuture())

这就是它的全部内容!如果您使用 sink 订阅该合并,则它会收到 finished 完成或 failure 完成。你猜怎么着?它接收 failure 完成 当且仅当一个或两个 post 操作失败!它仅在它们都成功时接收 finished 完成,这正是你想知道什么。

作为测试平台,以下是您的 storeInformation 的示例实现(出于示例目的,我忽略了字符串):

var storage = Set<AnyCancellable>()
enum Oops : Error { case darn }
func storeInformation() {
    Publishers.Merge(storeClassesFuture(), storeFeaturesFuture())
        .receive(on: DispatchQueue.main)
        .sink { (completion) in
            switch completion {
            case .failure: print("at least one of them failed")
            case .finished: print("they both succeeded")
            }
            print("---")
        } receiveValue: { _ in }
        .store(in: &storage)
}

为了作为随机测试,这里有两个可以随机成功或失败的未来:

func storeClassesFuture() -> AnyPublisher<Void,Error> {
    Deferred {
        Future<Void,Error> { promise in
            if Bool.random() {
                print("storeClassesFuture succeeded")
                promise(.success(()))
            } else {
                print("storeClassesFuture failed")
                promise(.failure(Oops.darn))
            }
        }
    }.eraseToAnyPublisher()
}
func storeFeaturesFuture() -> AnyPublisher<Void,Error> {
    Deferred {
        Future<Void,Error> { promise in
            if Bool.random() {
                print("storeFeaturesFuture succeeded")
                promise(.success(()))
            } else {
                print("storeFeaturesFuture failed")
                promise(.failure(Oops.darn))
            }
        }
    }.eraseToAnyPublisher()
}

这里是重复调用 storeInformation 的一些示例输出:

storeClassesFuture succeeded
storeFeaturesFuture succeeded
they both succeeded
---
storeClassesFuture failed
storeFeaturesFuture failed
at least one of them failed
---
storeClassesFuture failed
storeFeaturesFuture succeeded
at least one of them failed
---
storeClassesFuture failed
storeFeaturesFuture failed
at least one of them failed
---
storeClassesFuture failed
storeFeaturesFuture succeeded
at least one of them failed
---
storeClassesFuture succeeded
storeFeaturesFuture succeeded
they both succeeded
---
storeClassesFuture succeeded
storeFeaturesFuture succeeded
they both succeeded
---
storeClassesFuture failed
storeFeaturesFuture succeeded
at least one of them failed
---
storeClassesFuture failed
storeFeaturesFuture succeeded
at least one of them failed
---
storeClassesFuture succeeded
storeFeaturesFuture succeeded
they both succeeded
---

如您所见,两个可失败的 Future 的合并完美地表达了您所追求的逻辑。

(这种事情是采用Combine框架而不是使用DispatchGroup的一个很好的理由。我发现我以前用DispatchGroup做的一切都可以用Combine做得更好。这恰好是一个特别明确的例子。 )

答案 1 :(得分:1)

这里有一个“AND”语义,所以你应该在你的代码中写下它:

let dispatchGroup = DispatchGroup()
var groupResult: Bool = true // identity for AND
dispatchGroup.enter()
storeFeatures { success in
  groupResult = groupResult && success // here!
  dispatchGroup.leave()
}

dispatchGroup.enter()
storeClasses { success in
  groupResult = groupResult && success // and here
  dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
  completion(groupResult)
}

当每个任务完成时,你想表达的想法

<块引用>

如果前一组结果为真且成功为真,则该组结果应为真