在Swift中有类似Java的“未来”吗?

时间:2014-10-23 23:10:08

标签: swift promise future promisekit

Java具有可以在新线程中运行任务的Future或FutureTask。然后,将执行结果返回到原始线程。 Swift中有任何功能可以实现吗?

6 个答案:

答案 0 :(得分:2)

不是由语言提供的(意思是标准库),但您可以自己滚动或只使用https://github.com/Thomvis/BrightFutures

等库

答案 1 :(得分:2)

您正在研究某种称为Futures and promises的语言结构。您可以找到一些示例,例如:

然而语言本身就错过了这样的功能。

答案 2 :(得分:1)

如果Apple确实在Swift中实施期货或承诺,他们会这样说吗?毕竟,他们总是避免谈论Future产品。 ;)

无论如何,最初的问题似乎一般是关于异步工作的方法,而不一定是用Futures / Promises风格模型专门做的。因此,虽然其他答案中提到的第三方库对于该模型非常有用,但您也可以使用相同的iOS& OS X内置API,您可以从ObjC:dispatchNSOperation。例如:

NSOperationQueue().addOperationWithBlock {
    // do background work
    NSOperationQueue.mainQueue().addOperationWithBlock {
        // back to main thread for follow up work
    }
}

答案 3 :(得分:0)

现在还有FutureKit 与BrightFuture类似,但组成更像BFTask

我应该提到Bolts BFTask,虽然用Objective-C编写,但也是一个很好的候选者。 (现在在iOS iOS SDK中使用)

答案 4 :(得分:0)

我最终得到了基于OperationOperationQueue类的以下解决方案(仅限iOS SDK,Swift 3):

简而言之:将代码包装到同步或异步操作中。使用实用程序类链接操作。将操作添加到串行队列中。

如果出现错误,则无需取消当前操作,只需跳过实际代码即可。此外,异步执行块必须调用finalize回调以通知操作队列完成。可选地,DispatchQueue可以作为参数提供。代码块将在该队列上异步执行。

fileprivate func publishProductOnWebsite(listing: Listing) {
      var resultSKU: String?
      var resultError: Swift.Error?
      let chain = OperationsChain{ isExecuting, finalize in
         let task = ServerAPI.create(publishInfo: listing.publishInfo) { sku, error in
            guard isExecuting() else {
               return // We are canceled. Nothing to do.
            }
            if let error = error {
               resultError = error
            } else if let sku = sku {
               resultSKU = sku // Arbitrary thread. But OK as this example for serial operation queue.
            }
            finalize() // This will finish asynchronous operation
         }
         task.resume()
      }
      chain.thenAsync(blockExecutionQueue: DispatchQueue.main) { _, finalize in
         if let sku = resultSKU {
            listing.sku = sku
            DBStack.mainContext.saveIfHasChanges(savingParent: true) { error in
               resultError = error
               finalize()
            }
         } else {
            finalize()
         }
      }
      chain.thenSync(blockExecutionQueue: DispatchQueue.main) { [weak self] in
         if let error = resultError {
            self?.handleError(error) // Executed on Main thread.
         } else {
            self?.trackPublish()
            self?.eventHandler?(.publishCompleted)
         }
      }
      operationQueue.cancelAllOperations()
      operationQueue.addOperations(chain.operations, waitUntilFinished: false)
}

OperationsChain 类:将代码块包含到Operation中,并将操作保存到operations数组维护依赖项中。

public class OperationsChain {

   public private(set) var operations = [Operation]()

   public init(blockExecutionQueue: DispatchQueue? = nil,
               executionBlock: @escaping AsynchronousBlockOperation.WorkItemBlock) {
      let op = AsynchronousBlockOperation(blockExecutionQueue: blockExecutionQueue, executionBlock: executionBlock)
      operations.append(op)
   }

   public init(blockExecutionQueue: DispatchQueue? = nil,
               executionBlock: @escaping SynchronousBlockOperation.WorkItemBlock) {
      let op = SynchronousBlockOperation(blockExecutionQueue: blockExecutionQueue, executionBlock: executionBlock)
      operations.append(op)
   }

   @discardableResult
   public func thenAsync(blockExecutionQueue: DispatchQueue? = nil,
                         executionBlock: @escaping AsynchronousBlockOperation.WorkItemBlock) -> AsynchronousBlockOperation {
      let op = AsynchronousBlockOperation(blockExecutionQueue: blockExecutionQueue, executionBlock: executionBlock)
      if let lastOperation = operations.last {
         op.addDependency(lastOperation)
      } else {
         assertionFailure()
      }
      operations.append(op)
      return op
   }

   @discardableResult
   public func thenSync(blockExecutionQueue: DispatchQueue? = nil,
                        executionBlock: @escaping SynchronousBlockOperation.WorkItemBlock) -> SynchronousBlockOperation {
      let op = SynchronousBlockOperation(blockExecutionQueue: blockExecutionQueue, executionBlock: executionBlock)
      if let lastOperation = operations.last {
         op.addDependency(lastOperation)
      } else {
         assertionFailure()
      }
      operations.append(op)
      return op
   }

}

SynchronousBlockOperation AsynchronousBlockOperation 类。

public final class SynchronousBlockOperation: Operation {

   public typealias WorkItemBlock = (Void) -> Void

   fileprivate var executionBlock: WorkItemBlock?
   fileprivate var blockExecutionQueue: DispatchQueue?

   public init(blockExecutionQueue: DispatchQueue? = nil, executionBlock: @escaping SynchronousBlockOperation.WorkItemBlock) {
      self.blockExecutionQueue = blockExecutionQueue
      self.executionBlock = executionBlock
      super.init()
   }

   public override func main() {
      if let queue = blockExecutionQueue {
         queue.async { [weak self] in
            self?.executionBlock?()
         }
      } else {
         executionBlock?()
      }
   }
}

open class AsynchronousBlockOperation: AsynchronousOperation {

   public typealias FinaliseBlock = (Void) -> Void
   public typealias StatusBlock = (Void) -> Bool
   public typealias WorkItemBlock = (@escaping StatusBlock, @escaping FinaliseBlock) -> Void

   fileprivate var executionBlock: WorkItemBlock?
   fileprivate var blockExecutionQueue: DispatchQueue?

   public init(blockExecutionQueue: DispatchQueue? = nil, executionBlock: @escaping AsynchronousBlockOperation.WorkItemBlock) {
      self.blockExecutionQueue = blockExecutionQueue
      self.executionBlock = executionBlock
      super.init()
   }

   open override func onStart() {
      if let queue = blockExecutionQueue {
         queue.async { [weak self] in
            self?.executionBlock?({ return self?.isExecuting ?? false }) {
               self?.finish()
            }
         }
      } else {
         executionBlock?({ [weak self] in return self?.isExecuting ?? false }) { [weak self] in
            self?.finish()
         }
      }
   }
}

AsynchronousOperation 类:Operation的可重用子类。

open class AsynchronousOperation: Operation {

   fileprivate var lockOfProperties = NonRecursiveLock.makeDefaultLock()
   fileprivate var lockOfHandlers = NonRecursiveLock.makeDefaultLock()

   fileprivate var mFinished = false
   fileprivate var mExecuting = false    
}

extension AsynchronousOperation {

   public final override var isAsynchronous: Bool {
      return true
   }

   public final override var isExecuting: Bool {
      return lockOfProperties.synchronized { mExecuting }
   }

   public final override var isFinished: Bool {
      return lockOfProperties.synchronized { mFinished }
   }

}

extension AsynchronousOperation {

   public final override func start() {
      if isCancelled || isFinished || isExecuting {
         return
      }
      willChangeValue(forKey: "isExecuting")
      lockOfProperties.synchronized { mExecuting = true }
      onStart()
      didChangeValue(forKey: "isExecuting")
   }

   public final override func cancel() {
      super.cancel()
      if isExecuting {
         onCancel()
         finish()
      } else {
         onCancel()
         lockOfProperties.synchronized {
            mExecuting = false
            mFinished = true
         }
      }
   }

   public final func finish() {
      willChangeValue(forKey: "isExecuting")
      willChangeValue(forKey: "isFinished")
      lockOfProperties.synchronized {
         mExecuting = false
         mFinished = true
      }
      onFinish()
      didChangeValue(forKey: "isExecuting")
      didChangeValue(forKey: "isFinished")
   }

}

extension AsynchronousOperation {

   /// Subclasses must launch job here.
   ///
   /// **Note** called between willChangeValueForKey and didChangeValueForKey calls, but after property mExecuting is set.
   open func onStart() {
   }

   /// Subclasses must cancel job here.
   ///
   /// **Note** called immediately after calling super.cancel().
   open func onCancel() {
   }

   /// Subclasses must release job here.
   ///
   /// **Note** called between willChangeValueForKey and didChangeValueForKey calls,
   /// but after properties mExecuting and mFinished are set.
   open func onFinish() {
   }

}

答案 5 :(得分:0)

[Java Future and Promise]

Swift 的 Combine framework 使用这些结构