Controlling Where Callbacks Execute

  • An executor calls closures submitted to it, typically in first-in, first-out order on some other thread. An executor may also model locks or atomicity.

    Throughout the Deferred module, upon methods (or parameters to methods built around upon, such as map) are overloaded to take an Executor as well as the standard DispatchQueue.

    A custom executor is a customization point into the asynchronous semantics of a future, and may be important for ensuring the thread safety of an upon closure.

    For instance, the concurrency model of Apple’s Core Data framework requires that objects be accessed from other threads using the perform(_:) method, and not just thread isolation. Here, we connect that to Deferred:

    extension NSManagedObjectContext: Executor {
    
         func submit(body: @escaping() -> Void) {
             perform(body)
         }
    
    }
    

    And use it like you would a dispatch queue, with upon:

    let context: NSManagedObjectContext = ...
    let personJSON: Future<JSON> = ...
    let person: Future<Person> = personJSON.map(upon: context) { json in
        Person(json: json, inContext: context)
    }
    
    See more

    Declaration

    Swift

    public protocol Executor : AnyObject
  • Dispatch queues invoke function bodies submitted to them serially in FIFO order. A queue will only invoke one-at-a-time, but independent queues may each invoke concurrently with respect to each other.

    See more

    Declaration

    Swift

    extension DispatchQueue: Executor
  • An operation queue manages a number of operation objects, making high level features like cancellation and dependencies simple.

    As an Executor, upon closures are enqueued as non-cancellable operations. This is ideal for regulating the call relative to other operations in the queue.

    See more

    Declaration

    Swift

    extension OperationQueue: Executor
  • A run loop processes events on a thread, and is a fundamental construct in Cocoa applications.

    As an Executor, submitted functions are invoked on the next iteration of the run loop.

    See more

    Declaration

    Swift

    extension RunLoop: Executor
  • A run loop processes events on a thread, and is a fundamental construct in Cocoa applications.

    As an Executor, submitted functions are invoked on the next iteration of the run loop.

    See more

    Declaration

    Swift

    extension CFRunLoop: Executor