GithubHelp home page GithubHelp logo

andrewbarba / bluebird.swift Goto Github PK

View Code? Open in Web Editor NEW
41.0 3.0 2.0 677 KB

Promise/A+, Bluebird inspired, implementation in Swift 5

License: MIT License

Swift 98.54% Ruby 0.76% Makefile 0.44% C 0.26%
bluebird swift async control-flow promise concurrency

bluebird.swift's Introduction

Bluebird.swift

CocoaPods Compatible Carthage Compatible Twitter

Promise/A+ compliant, Bluebird inspired, implementation in Swift 5

Features

  • Promise/A+ Compliant
  • Swift 5
  • Promise Cancellation
  • Performance
  • Lightweight
  • Unit Tests
  • 100% Documented

Documentation

https://andrewbarba.github.io/Bluebird.swift/

Requirements

  • iOS 9.0+ / macOS 10.11+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 10.2
  • Swift 5

Installation

Swift Package Manager

// swift-tools-version:5.0

import PackageDescription

let package = Package(
    name: "My App",
    dependencies: [
        .package(url: "https://github.com/AndrewBarba/Bluebird.swift.git", from: "5.1.0")
    ]
)

CocoaPods

CocoaPods 1.5.0+ is required to build Bluebird

pod 'Bluebird', '~> 5.0'

Carthage

github "AndrewBarba/Bluebird.swift" ~> 5.0

Who's Using Bluebird

Using Bluebird in production? Let me know with a Pull Request or an Issue.

Usage

Promise

Promises are generic and allow you to specify a type that they will eventually resolve to. The preferred way to create a Promise is to pass in a closure that accepts two functions, one to be called to resolve the Promise and one to be called to reject the Promise:

let promise = Promise<Int> { resolve, reject in
  // - resolve(someInt)
  // - reject(someError)
}

The resolve and reject functions can be called asynchronously or synchronously. This is a great way to wrap existing Cocoa API to resolve Promises in your own code. For example, look at an expensive function that manipulates an image:

Before Promises
func performExpensiveOperation(onImage image: UIImage, completion: @escaping (UIImage?, Error?) -> Void) {
  DispatchQueue(label: "image.operation").async {
    do {
      let image = try ...
      completion(image, nil)
    } catch {
      completion(nil, error)
    }
  }
}
After Promises
func performExpensiveOperation(onImage image: UIImage) -> Promise<UIImage> {
  return Promise<UIImage> { resolve, reject in
    DispatchQueue(label: "image.operation").async {
      do {
        let image = try ...
        resolve(image)
      } catch {
        reject(error)
      }
    }
  }
}

Okay, so the inner body of the function looks almost identical... But look at how much better the function signature looks!

No more completion handler, no more optional image, no more optional error. Optionals in the original function are a dead giveaway that you'll be guarding and unwrapping in the near future. With the Promise implementation that logic is hidden by good design. Using this new function is now a joy:

let original: UIImage = ...

performExpensiveOperation(onImage: original)
  .then { newImage in
    // do something with the new image
  }
  .catch { error in
    // something went wrong, handle the error
  }

then

You can easily perform a series of operations with the then method:

authService.login(email: email, password: password)
  .then { auth in userService.read(with: auth) }
  .then { user in favoriteService.list(for: user) }
  .then { favorites in ... }

Notice each time you return a Promise (or a value) from a then handler, the next then handler receives the resolution of that handler, waiting for the previous to fully resolve. This is extremely powerful for asynchronous control flow.

Grand Central Dispatch

Any method in Bluebird that accepts a handler also accepts a DispatchQueue so you can control what queue you want the handler to run on:

userService.read(id: "123")
  .then(on: backgroundQueue) { user -> UIImage in
    let image = UIImage(user: user)
    ... perform complex image operation ...
    return image
  }
  .then(on: .main) { image in
    self.imageView.image = image
  }

By default all handlers are run on the .main queue.

catch

Use catch to handle / recover from errors that happen in a Promise chain:

authService.login(email: email, password: password)
  .then { auth in userService.read(with: auth) }
  .then { user in favoriteService.list(for: user) }
  .then { favorites in ... }
  .catch { error in
    self.present(error: error)
  }

Above, if any then handler throws an error, or if one of the Promises returned from a handler rejects, then the final catch handler will be called.

You can also perform complex recovery when running multiple asynchronous operations:

Bluebird.try { performFirstOp().catch(handleOpError) }
  .then { performSecondOp().catch(handleOpError) }
  .then { performThirdOp().catch(handleOpError) }
  .then { performFourthOp().catch(handleOpError) }
  .then {
    // all completed
  }

tap

Useful for performing an operation in the middle of a promise chain without changing the type of the Promise:

authService.login(email: email, password: password)
  .tap { auth in print(auth) }
  .then { auth in userService.read(with: auth) }
  .tap { user in print(user) }
  .then { user in favoriteService.list(for: user) }
  .then { favorites in ... }

You can also return a Promise from the tap handler and the chain will wait for that promise to resolve:

authService.login(email: email, password: password)
  .then { auth in userService.read(with: auth) }
  .tap { user in userService.updateLastActive(for: user) }
  .then { user in favoriteService.list(for: user) }
  .then { favorites in ... }

finally

With finally you can register a handler to run at the end of a Promise chain, regardless of it's result:

spinner.startAnimating()

authService.login(email: email, password: "bad password")
  .then { auth in userService.read(with: auth) } // will not run
  .then { user in favoriteService.list(for: user) } // will not run
  .finally { // this will run!
    spinner.stopAnimating()
  }
  .catch { error in
    // handle error
  }

join

Join different types of Promises seamlessly:

join(fetchArticle(id: "123"), fetchAuthor(id: "456"))
  .then { article, author in
    // ...
  }

map

Iterate over a sequence of elements and perform an operation each:

let articles = ...

map(articles) { article in
  return favoriteService.like(article: article)
}.then { _ in
  // all articles liked successfully
}.catch { error in
  // handle error
}

You can also iterate over a sequence in series using mapSeries().

reduce

Iterate over a sequence and reduce down to a Promise that resolves to a single value:

let users = ...

reduce(users, 0) { partialTime, user in
  return userService.getActiveTime(for: user).then { time in
    return partialTime + time
  }
}.then { totalTime in
  // calculated total time spent in app
}.catch { error in
  // handle error
}

all

Wait for all promises to complete:

all([
  favoriteService.like(article: article1),
  favoriteService.like(article: article2),
  favoriteService.like(article: article3),
  favoriteService.like(article: article4),
]).then { _ in
  // all articles liked
}

any

Easily handle race conditions with any, as soon as one Promise resolves the handler is called and will never be called again:

let host1 = "https://east.us.com/file"
let host2 = "https://west.us.com/file"

any(download(host1), download(host2))
  .then { data in
    ...
  }

try

Start off a Promise chain:

// Prefix with Bluebird since try is reserved in Swift
Bluebird.try {
  authService.login(email: email, password: password)
}.then { auth in
  // handle login
}.catch { error in
  // handle error
}

Tests

Tests are continuously run on Bitrise. Since Bitrise doesn't support public test runs I can't link to them, but you can run the tests yourself by opening the Xcode project and running the tests manually from the Bluebird scheme.

Bluebird vs PromiseKit

I'd be lying if I said PromiseKit wasn't a fantastic library (it is!) but Bluebird has different goals that may or may not appeal to different developers.

Xcode 9+ / Swift 4+

PromiseKit goes to great length to maintain compatibility with Objective-C, previous versions of Swift, and previous versions of Xcode. Thats a ton of work, god bless them.

Generics & Composition

Bluebird has a more sophisticated use of generics throughout the library giving us really nice API for composing Promise chains in Swift.

Bluebird supports map, reduce, all, any with any Sequence type, not just arrays. For example, you could use Realm's List or Result types in all of those functions, you can't do this with PromiseKit.

Bluebird also supports Promise.map and Promise.reduce (same as Bluebird.js) which act just like their global equivalent, but can be chained inline on an existing Promise, greatly enhancing Promise composition.

No Extensions

PromiseKit provides many useful framework extensions that wrap core Cocoa API's in Promise style functions. I currently have no plans to provide such functionality, but if I did, it would be in a different repository so I can keep this one lean and well tested.

Bluebird API Compatible

I began using PromiseKit after heavily using Bluebird.js in my Node/JavaScript projects but became annoyed with the subtle API differences and a few things missing all together. Bluebird.swift attempts to closely follow the API of Bluebird.js:

Bluebird.js
Promise.resolve(result)
Promise.reject(error)
promise.then(handler)
promise.catch(handler)
promise.finally(() => ...)
promise.tap(value => ...)
Bluebird.swift
Promise(resolve: result)
Promise(reject: error)
promise.then(handler)
promise.catch(handler)
promise.finally { ... }
promise.tap { value in ... }
PromiseKit
Promise(value: result)
Promise(error: error)
promise.then(execute: handler)
promise.catch(execute: handler)
promise.always { ... }
promise.tap { result in
  switch result {
  case .fullfilled(let value):
    ...
  case .rejected(let error):
    ...
  }
}

These are just a few of the differences, and Bluebird.swift is certainly missing features in Bluebird.js, but my goal is to close that gap and keep maintaining an API that much more closely matches where applicable.

bluebird.swift's People

Contributors

andrewbarba avatar devioustree avatar jeffremer avatar mattrobmattrob avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

bluebird.swift's Issues

Q: How to create a pending Promise?

RT.

I'm writing code to wrap the delegation pattern to Promise.

Can I create a pending promise?

I'm new to Promise/Future Programming, and I find it is not obvious to create a pending promise with Bluebird.swift.

Some other problems:
How to get value 1 & value 2 in the 3rd `then closure?

Carthage Bluebird.swift framework is missing CFBundleVersion

Carthage Bluebird.swift framework (Bluebird.framework/Info.plist) is missing CFBundleVersion.

From CFBundleVersion:

This key is required by the App Store and is used throughout the system to identify the version of the build. For macOS apps, increment the build version before you distribute a build.

ITMS error with framework bundled in App.app/Frameworks via Carthage:

ERROR ITMS-90056: "This bundle Payload/App.app/Frameworks/Bluebird.framework is invalid. The Info.plist file is missing the required key: CFBundleVersion. Please find more information about CFBundleVersion at https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleversion"

Finalize catch/then semantics

One of the hardest challenges of a Promise implementation in a strongly typed language is the semantics of catch and how it affects the Promise chain:

Promise/A+ 2.2.7.1
If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure Resolve(promise2, x)

With this requirement, any then called directly after a catch does not know the Type of the first argument in it's handler. If the prior Promise resolves, then it will be the resolution of that Promise, but if it rejects it will be whatever value the catch returns. This unknown makes it impossible to implement directly in a typed language and forces us to make tradeoffs either with more functions (different names that explicitly indicate which behavior they implement) or making the resolution type less strict perhaps by using an optional type or a Any and then forcing unwrapping in the then handler.

I'm curious what the community's thoughts are on this before changing the semantics again in this library. If/when there is a good solution I will release a new version of the library as 2.0.0.

For reference, the current implementation provides 2 functions: catch and catchThen:

  • catch allows for catching an error and continuing the promise chain as Promise<Void>. Whether the prior promise resolves/rejects, the then handler after a catch will always be run.
  • catchThen forces the handler to recover with the same result Type as the original Promise. This means that if the original Promise resolves we can pass that result down to any then handlers after the catch and if it rejects the catch will be responsible for providing an alternate resolution of the same type.

Promise<Void>.resolve()

Hi there! At first I'd like to say that you did a great job creating this promise framework!
I'm thinking on migrating from closure-style async API to promise-style, and I need your help here.

Sometimes needed to not pass any argument in a resolve block of promise, this is where Promise appears. Whenever I call resolve() on such promise, it requires an arguments, which doesn't make sense.
What I'm asking for is: can you please add a function with signature without any parameter for void-parametrized promise? Thanks in advance.

Related image: https://imgur.com/fGtH99j

Using with Swift package manager

I tried to import Bluebird into command line app using Swift package manager. It wouldn't compile and was giving following error:

error: use of undeclared type 'DispatchQueue'

I had to add "import Foundation" to all Bluebird's files to make it compile. Is there any reason why it was omitted? Did I miss some configuration? Meanwhile Alamofire compiled right away..

Missing support for binary frameworks with module stability

Bluebird.xcodeproj isn't configured to generate a .swiftinterface file which means dynamic frameworks can only be used with projects using the same version of the Swift compiler.

It would be nice to not have to recompile the framework when a new Swift compiler is released.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.