Futures and Promises

  • A value that may become determined (or filled) at some point in the future. Once determined, it cannot change.

    You may subscribe to be notified once the value becomes determined.

    Handlers and their captures are strongly referenced until:

    • they are executed when the value is determined
    • the last copy to this type escapes without the value becoming determined

    If the value never becomes determined, a handler submitted to it will never be executed.

    See more

    Declaration

    Swift

    public struct Deferred<Value>
  • A future models reading a value which may become available at some point.

    A FutureProtocol may be preferable to an architecture using completion handlers; separating the mechanism for handling the completion from the call that began it leads to a more readable code flow.

    A future is primarily useful as a joining mechanism for asynchronous operations. Though the protocol requires a synchronous accessor, its use is not recommended outside of testing. upon is preferred for nearly all access:

    myFuture.upon(.main) { value in
      print("I now have the value: \(value)")
    }
    

    FutureProtocol makes no requirement on conforming types regarding thread-safe access, though ideally all members of the future could be called from any thread.

    See more

    Declaration

    Swift

    public protocol FutureProtocol : CustomDebugStringConvertible, CustomReflectable
  • A promise models writing the result of some asynchronous operation.

    Promises should generally only be determined, or filled, once. This allows an implementing type to clear a queue of subscribers, for instance, and provides consistent sharing of the determined value.

    An implementing type should discourage race conditions around filling. However, certain use cases inherently race (such as cancellation). Any attempts to check for programmer error should be active by default.

    See more

    Declaration

    Swift

    public protocol PromiseProtocol