• Stars
    star
    264
  • Rank 155,075 (Top 4 %)
  • Language
    Swift
  • License
    Other
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

โฐ A lightweight implementation of Promises in Swift

When

CI Status Version Carthage Compatible License Platform

Description

When is a lightweight implementation of Promises in Swift. It doesn't include any helper functions for iOS and OSX and it's intentional, to remove redundant complexity and give you more freedom and flexibility in your choices. It is type safe, thanks Swift generics, so you could create promises with whatever type you want.

When can easily be integrated into your projects and libraries to move your asynchronous code up to the next level.

Table of Contents

When Icon

Why?

To make asynchronous code more readable and standardized:

fetchJSON().then({ data: NSData -> [[String: AnyObject]] in
  // Convert to JSON
  return json
}).then({ json: [[String: AnyObject]] -> [Entity] in
  // Map JSON
  // Save to database
  return items
}).done({ items: [Entity] in
  self.items = items
  self.tableView.reloadData()
}).error({ error in
  print(error)
})

Usage

Promise

A promise represents the future value of a task. Promises start in a pending state and then could be resolved with a value or rejected with an error.

// Creates a new promise that could be resolved with a String value
let promise = Promise<String>()
// Resolves the promise
promise.resolve("String")
// Or rejects the promise
promise.reject(Error.notFound)
// Creates a new promise that is resolved with a String value
let promise = Promise({
  return "String"
})
// Creates a new promise that is rejected with an Error
let promise = Promise({
  //...
  throw Error.notFound
})

Callbacks of the current promise and all the chained promises (created with then) are executed on the main queue by default, but you can always specify the needed queue in init:

let promise = Promise<String>(queue: dispatch_get_main_queue())

Done

Adds a handler to be called when the promise object is resolved with a value:

// Create a new promise in a pending state
let promise = Promise<String>()
// Add done callback
promise.done({ value in
  print(value)
})
// Resolve the promise
promise.resolve("String")

Fail

Adds a handler to be called when the promise object is rejected with an Error:

// Create a new promise in a pending state
let promise = Promise<String>()
// Add fail callback
promise.fail({ error in
  print(error)
})
// Reject the promise
promise.reject(Error.notFound)

It's also possible to cancel a promise, which means it will be rejected with PromiseError.cancelled error. FailurePolicy can be used if you want to ignore this error in your fail handler:

// Create a new promise in a pending state
let promise = Promise<String>()
// This callback will not be called when a promise is cancelled
promise.fail({ error in
  print(error)
})
// This callback will be called when a promise is cancelled
promise.fail(policy: .allErrors, { error in
  print(error)
})
// Cancel the promise
promise.cancel()

Always

Adds a handler to be called when the promise object is either resolved or rejected. This callback will be called after done or fail handlers.

// Create a new promise in a pending state
let promise = Promise<String>()
// Add always callback
promise.always({ result in
  switch result {
  case let .success(value):
    print(value)
  case let .failure(error):
    print(error)
  }
})
// Resolve or reject the promise
promise.resolve("String") // promise.reject(Error.notFound)

Then

Returns a new promise that can use the result value of the current promise. It means that you could easily create chains of promises to simplify complex asynchronous operations into clear and simple to understand logic.

A new promise is resolved with the value returned from the provided closure:

let promise = Promise<NSData>()

promise
  .then({ data -> Int in
    return data.length
  }).then({ length -> Bool in
    return length > 5
  }).done({ value in
    print(value)
  })

promise.resolve("String".dataUsingEncoding(NSUTF8StringEncoding)!)

A new promise is resolved when the promise returned from the provided closure resolves:

struct Networking {
  static func GET(url: NSURL) -> Promise<NSData> {
    let promise = Promise<NSData>()
    //...
    return promise
  }
}

Networking.GET(url1)
  .then({ data -> Promise<NSData> in
    //...
    return Networking.GET(url2)
  }).then({ data -> Int in
    return data.length
  }).done({ value in
    print(value)
  })

then closure is executed on the main queue by default, but you can pass a needed queue as a parameter:

promise.then(on: dispatch_get_global_queue(QOS_CLASS_UTILITY, 0))({ data -> Int in
  //...
})

If you want to use background queue there are the helper methods for this case:

promise1.thenInBackground({ data -> Int in
  //...
})

promise2.thenInBackground({ data -> Promise<NSData> in
  //...
})

Recover

Returns a new promise that can be used to continue the chain when an error was thrown.

let promise = Promise<String>()
// Recover the chain
promise
  .recover({ error -> Promise<String> in
    return Promise({
      return "Recovered"
    })
  })
  .done({ string in
    print(string) // Recovered
  })
// Reject the promise
promise.reject(Error.notFound)

When

Provides a way to execute callback functions based on one or more promises. The when method returns a new "master" promise that tracks the aggregate state of all the passed promises. The method will resolve its "master" promise as soon as all the promises resolve, or reject the "master" promise as soon as one of the promises is rejected. If the "master" promise is resolved, the done callback is executed with resolved values for each of the promises:

let promise1 = Promise<Int>()
let promise2 = Promise<String>()
let promise3 = Promise<Int>()

when(promise1, promise2, promise3)
  .done({ value1, value2, value3 in
    print(value1)
    print(value2)
    print(value3)
  })

promise1.resolve(1)
promise2.resolve("String")
promise3.resolve(3)

Reactive extensions

Use the following extension in order to integrate When with RxSwift:

import RxSwift

extension Promise: ObservableConvertibleType {
  public func asObservable() -> Observable<T> {
    return Observable.create({ observer in
      self
        .done({ value in
          observer.onNext(value)
        })
        .fail({ error in
          observer.onError(error)
        })
        .always({ _ in
          observer.onCompleted()
        })

      return Disposables.create()
    })
  }
}

Installation

When is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'When'

For RxSwift extensions you can use CocoaPods subspecs:

pod 'When/RxSwift'

When is also available through Carthage. To install just write into your Cartfile:

github "vadymmarkov/When"

Author

Vadym Markov, [email protected]

Credits

Credits for inspiration go to PromiseKit and Then.

Contributing

Check the CONTRIBUTING file for more info.

License

When is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

Fakery

๐Ÿ‘ฝ Swift fake data generator
Swift
1,786
star
2

Beethoven

๐ŸŽธ A maestro of pitch detection.
Swift
810
star
3

Malibu

๐Ÿ„ Malibu is a networking library built on promises
Swift
414
star
4

MARKRangeSlider

A custom reusable slider control with 2 thumbs (range slider).
Objective-C
186
star
5

Pitchy

๐ŸŽผ A simple way to get a music pitch from a frequency.
Swift
163
star
6

Fashion

๐Ÿ’… Fashion accessories and beauty tools to share and reuse UI styles in a Swifty way
Swift
132
star
7

RetroProgress

๐Ÿ’ˆ Retro looking progress bar straight from the 90s
Swift
83
star
8

PinFloyd

MapKit annotations clustering for iOS
Swift
27
star
9

MARKCircularSlider

An easy-to-use circular slider
Objective-C
25
star
10

TVShowroom

An app that demonstrates standard tvOS interface elements.
Swift
19
star
11

Rexy

๐Ÿฒ POSIX Regular Expressions in Swift
Swift
16
star
12

reviewery-mobile

iOS application to rate songs in Spotify playlists
JavaScript
16
star
13

geobot

A simple chat bot built using Wit.ai and Vapor Swift web framework.
Swift
15
star
14

Kontena

IOC container in Swift
Swift
6
star
15

MARKTempoMeter

A simple tool to determine the BPM (beats per minute).
Objective-C
6
star
16

novel-cli

Novel CMS command line interface.
Swift
4
star
17

TypeHelper

A simple function for getting the name of the non optional type in Swift.
Swift
4
star
18

SpeechNotes

Speech-To-Text iOS demo application
Swift
4
star
19

Mentions

Swift
3
star
20

reviewery-server

Node.js server for Reviewery iOS application.
JavaScript
3
star
21

novel-template

A basic template for creating a new Novel Swift CMS application.
CSS
2
star
22

novel-demo

Demo for Novel Swift CMS.
JavaScript
2
star
23

UIImage-MARKColorizer

UIImage category for image colorizing
Objective-C
2
star
24

UIImageView-MARKColorizer

UIImageView category for image colorizing
Objective-C
2
star
25

vadymmarkov.github.io

โ–ผ A simple portfolio static website built in Jekyll
HTML
2
star
26

Limb

ยฏ\_(ใƒ„)_/ยฏ
Shell
1
star