Lightweight promises for iOS, macOS, tvOS, watchOS, and Linux

Overview

Futures

Tests

Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understand.

Supported Platforms

  • Ubuntu 14.04
  • macOS 10.9
  • tvOS 9.0
  • iOS 8.0
  • watchOS 2.0

Architecture

Fundamentally, Futures is a very simple framework, that consists of two types:

  • Promise, a single assignment container producing a Future
  • Future, a read-only container resolving into either a value, or an error

In many promise frameworks, a promise is undistinguished from a future. This introduces mutability of a promise that gets passed around. In Futures, a Future is the observable value while a Promise is the function that sets the value.

Futures are observed, by default, on a single concurrent dispatch queue. This queue can be modified by assigning a different queue to DispatchQueue.futures. You can also specify a queue of your choice to each callback added to a future .

A future is regarded as:

  • resolved, if its value is set
  • fulfilled, if the value is set, and successful
  • rejected, if the value is set, and a failure (error)

Usage

When a function returns a Future<Value>, you can either decide to observe it directly, or continue with more asynchronous tasks. For observing, you use:

  • whenResolved, if you're interested in both a value and a rejection error
  • whenFulfilled, if you only care about the values
  • whenRejected, if you only care about the error

If you have more asynchronous work to do based on the result of the first future, you can use

  • flatMap(), to execute another future based on the result of the current one
  • flatMapIfRejected(), to recover from a potential error resulting from the current future
  • flatMapThrowing(), to transform the fulfilled value of the current future or return a rejected future
  • map(), to transform the fulfilled value of the current future
  • recover(),to transform a rejected future into a fulfilled future
  • always(), to execute a Void returning closure regardless of whether the current future is rejected or resolved
  • and(), to combine the result of two futures into a single tuple
  • Future<T>.reduce(), to combine the result of multiple futures into a single future

Note that you can specify an observation dispatch queue for all these functions. For instance, you can use flatMap(on: .main), or .map(on: .global()). By default, the queue is DispatchQueue.futures.

As a simple example, this is how some code may look:

let future = loadNetworkResource(
    from: URL("http://someHost/resource")!
).flatMapThrowing { data in
    try jsonDecoder.decode(SomeType.self, from: data)
}.always {
    someFunctionToExecuteRegardless()
}

future.whenFulfilled(on: .main) { someType in
    // Success
}

future.whenRejected(on: .main) { error in
    // Error
}

To create your functions returning a Future<T>, you create a new pending promise, and resolve it when appropriate.

func performAsynchronousWork() -> Future<String> {
    let promise = Promise<String>()

    DispatchQueue.global().async {
        promise.fulfill(someString)

        // If error
        promise.reject(error)
    }

    return promise.future
}

You can also use shorthands.

promise {
     try jsonDecoder.decode(SomeType.self, from: data)
} // Future<SomeType>

Or shorthands which you can return from asynchronously.

promise(String.self) { completion in
    /// ... on success ...
    completion(.fulfill("Some string"))
    /// ... if error ...
    completion(.reject(anError))
} // Future<String>

Documentation

The complete documentation can be found here.

Getting started

Futures can be added to your project either using Carthage or Swift package manager.

If you want to depend on Futures in your project, it's as simple as adding a dependencies clause to your Package.swift:

dependencies: [
    .package(url: "https://github.com/davidask/Futures.git", from: "1.6.0")
]

Or, add a dependency in your Cartfile:

github "davidask/Futures"

More details on using Carthage can be found here.

Lastly, import the module in your Swift files

import Futures

Contribute

Please feel welcome contributing to Futures, check the LICENSE file for more info.

Credits

David Ask

You might also like...
A promises library written in Swift featuring combinators like map, flatMap, whenAll, whenAny.
A promises library written in Swift featuring combinators like map, flatMap, whenAll, whenAny.

Promissum is a promises library written in Swift. It features some known functions from Functional Programming like, map and flatMap. It has useful co

NotificationCenter based Lightweight UI / AnyObject binder.
NotificationCenter based Lightweight UI / AnyObject binder.

Continuum NotificationCenter based Lightweight UI / AnyObject binder. final class ViewController: UIViewController { @IBOutlet weak var label: UI

A dead-simple abstraction over the iOS BackgroundTask API to make background tasks easy to isolate, maintain and schedule
A dead-simple abstraction over the iOS BackgroundTask API to make background tasks easy to isolate, maintain and schedule

A dead-simple abstraction over the iOS BackgroundTask API to make background tasks easy to isolate, maintain and schedule. Designed to be as lightweight and flexible as possible while tightly integrating with the system APIs. And It's built with Swift Concurrency in mind.

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety
A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety. Type Safe No more userInfo dictionary and Downcasting,

A publish/subscribe EventBus optimized for iOS

SwiftEventBus Allows publish-subscribe-style communication between components without requiring the components to explicitly be aware of each other Fe

Material para a apresentação da palestra "Implementando Interesses Transversais - um papo sobre arquitetura, DI e Design Patterns em Swift/iOS" no TDC Future 2021

--- title: Implementando Interesses Transversais - um papo sobre arquitetura, DI e Design Patterns em Swift/iOS author: Cícero Camargo date: Nov 30th

Easy to use and lightweight logger for iOS, macOS, tvOS, watchOS and Linux in Swift.
Easy to use and lightweight logger for iOS, macOS, tvOS, watchOS and Linux in Swift.

Lighty Easy to use and lightweight logger for iOS, macOS, tvOS, watchOS and Linux in Swift. Screenshots Requirements Lighty Version Minimum iOS Target

TraceLog is a highly configurable, flexible, portable, and simple to use debug logging system for Swift and Objective-C applications running on Linux, macOS, iOS, watchOS, and tvOS.

Please star this github repository to stay up to date. TraceLog Introduction TraceLog is a highly configurable, flexible, portable, and simple to use

A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.
A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.

Mechanica A library of Swift utils to ease your iOS, macOS, watchOS, tvOS and Linux development. Requirements Documentation Installation License Contr

A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Turf.js.

Turf for Swift 📱 🖥 💻 📺 ⌚️ A spatial analysis library written in Swift for native iOS, macOS, tvOS, watchOS, and Linux applications, ported from Tu

The hassle-free way to add Segment analytics to your Swift app (iOS/tvOS/watchOS/macOS/Linux).

Analytics-Swift The hassle-free way to add Segment analytics to your Swift app (iOS/tvOS/watchOS/macOS/Linux/iPadOS). Analytics helps you measure your

SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

A lightweight and powerful editor for localizing iOS, macOS, tvOS, and watchOS applications.
A lightweight and powerful editor for localizing iOS, macOS, tvOS, and watchOS applications.

It is Strings but with a Z 😬 Loved the project? Please share it with your friends and give it a ⭐️ Stringz is a lightweight and powerful editor that

SwiftyStoreKit is a lightweight In App Purchases framework for iOS, tvOS, watchOS, macOS, and Mac Catalyst ⛺
SwiftyStoreKit is a lightweight In App Purchases framework for iOS, tvOS, watchOS, macOS, and Mac Catalyst ⛺

SwiftyStoreKit is a lightweight In App Purchases framework for iOS, tvOS, watchOS, macOS, and Mac Catalyst. Features Super easy-to-use block-based API

Mercato is a lightweight In-App Purchases (StoreKit 2) library for iOS, tvOS, watchOS, macOS, and Mac Catalyst.
Mercato is a lightweight In-App Purchases (StoreKit 2) library for iOS, tvOS, watchOS, macOS, and Mac Catalyst.

Mercato Mercato is a lightweight In-App Purchases (StoreKit 2) library for iOS, tvOS, watchOS, macOS, and Mac Catalyst. Installation Swift Package Man

EventBroadcaster is a lightweight event handler framework, written in swift for iOS, macOS, tvOS & watchOS applications.
EventBroadcaster is a lightweight event handler framework, written in swift for iOS, macOS, tvOS & watchOS applications.

EventBroadcaster is a lightweight event handler framework, written in swift for iOS, macOS, tvOS & watchOS applications.

A wrapper to make it really easy to deal with iOS, macOS, watchOS and Linux Keychain and store your user's credentials securely.

A wrapper (written only in Swift) to make it really easy to deal with iOS, macOS, watchOS and Linux Keychain and store your user's credentials securely.

Lightweight Networking and Parsing framework made for iOS, Mac, WatchOS and tvOS.
Lightweight Networking and Parsing framework made for iOS, Mac, WatchOS and tvOS.

NetworkKit A lightweight iOS, Mac and Watch OS framework that makes networking and parsing super simple. Uses the open-sourced JSONHelper with functio

Releases(1.6.1)
Owner
David Ask
iOS developer at heart, former art director. Available for hire.
David Ask
⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 31, 2022
A Swift based Future/Promises Library for IOS and OS X.

FutureKit for Swift A Swift based Future/Promises Library for IOS and OS X. Note - The latest FutureKit is works 3.0 For Swift 2.x compatibility use v

null 759 Dec 2, 2022
Write great asynchronous code in Swift using futures and promises

BrightFutures How do you leverage the power of Swift to write great asynchronous code? BrightFutures is our answer. BrightFutures implements proven fu

Thomas Visser 1.9k Dec 20, 2022
The easiest Future and Promises framework in Swift. No magic. No boilerplate.

Promis The easiest Future and Promises framework in Swift. No magic. No boilerplate. Overview While starting from the Objective-C implementation of Ju

Alberto De Bortoli 111 Dec 27, 2022
Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.

Promises Promises is a modern framework that provides a synchronization construct for Objective-C and Swift to facilitate writing asynchronous code. I

Google 3.7k Dec 24, 2022
Futures and Promises library

#PureFutures A simple Futures and Promises library. ##Installation ###Carthage Add the following in your Cartfile: github "wiruzx/PureFutures" And ru

Victor Shamanov 17 Apr 5, 2019
Promises for Swift & ObjC.

Promises simplify asynchronous programming, freeing you up to focus on the more important things. They are easy to learn, easy to master and result in

Max Howell 14k Jan 5, 2023
Tame async code with battle-tested promises

Then Reason - Example - Documentation - Installation fetchUserId().then { id in print("UserID : \(id)") }.onError { e in print("An error occur

Fresh 963 Jan 3, 2023
FutureLib is a pure Swift 2 library implementing Futures & Promises inspired by Scala.

FutureLib FutureLib is a pure Swift 2 library implementing Futures & Promises inspired by Scala, Promises/A+ and a cancellation concept with Cancellat

Andreas Grosam 39 Jun 3, 2021
Easy Swift Futures & Promises.

❗️ Archived now ❗️ Since Apple released Combine framework, I decide to archive this repo. You still can use this repo as an example of Future/Promise

Dmytro Mishchenko 40 Sep 23, 2022