• Stars
    star
    747
  • Rank 58,314 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 8 years ago
  • Updated almost 3 years ago

Reviews

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

Repository Details

The ES8 Async/Await control flow for Swift

AwaitKit

Carthage Compatible Supported Platforms Version Build Status codecov.io codebeat badge Awesome

Have you ever dream to write asynchronous code like its synchronous counterpart?

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Internally it uses PromiseKit v6.10 to create and manage promises.

Requirements • Getting Started • Usage • Installation • Contribution • Contact • License

Requirements

  • iOS 8.0+
  • Xcode 8.0+
  • Swift 4.0+

Getting Started

If you want have a quick overview of the project take a look to this blog post.

Put simply, write this:

let user = try! await(signIn(username: "Foo", password: "Bar"))
try! await(sendWelcomeMailToUser(user))
try! await(redirectToThankYouScreen())

print("All done!")

Instead of:

signIn(username: "Foo", password: "Bar")
  .then { user in
    return self.sendWelcomeMailToUser(user)
  }
  .then { _ in
    return self.redirectToThankYouScreen()
  }
  .then { _ in
    print("All done!")
  }

Or worse, using the completion block imbrication hell style:

signIn(username: "Foo", password: "Bar") { user in
  self.sendWelcomeMailToUser(user) { _ in
    self.redirectToThankYouScreen() { _ in
      print("All done!")
    }
  }
}

Usage

Async

The async method yields the execution to its closure which will run in a background queue and returns a promise which will be resolved at this end of block.

Here a small example :

func setupNewUser(name: String) -> Promise<User> {  
  return async {
    let newUser = try await(self.createUser(name))
    let friends = try await(self.getFacebookFriends(name))

    newUser.addFriends(friends)

    return newUser
  }
}

Here the setupNewUser returns a promise with a user as value. If the end of async block is executed the promise will be resolved, otherwise if an error occurred inside the async block the promise will be rejected with the corresponding error.

The async block will catch the error thrown to reject the promise so you don't need to manage the await exceptions. But if necessary, you can:

async {
  do {
    try await(self.loginOrThrown(username: "yannickl"))
  }
  catch {
    print(error)
  }

  try await(self.clearCache())
}

Await

The await method will executes the given promise or block and await until it resolved or failed.

do {
  let name: String = try await {
    Thread.sleep(forTimeInterval: 0.2)

    if Int(arc4random_uniform(2) + 1) % 2 == 0 {
      return "yannickl"
    }
    else {
      throw NSError()
    }
  }

  print(name)
}
catch {
  print(error)
}

Custom queues

The async and await methods runs by default on a background concurrent queue. Of course, you can choose your own queues and call the following methods:

DispatchQueue.global(qos: .default).ak.async {

}

try DispatchQueue.global(qos: .default).ak.await {

}

When you use these methods and you are doing asynchronous, be careful to do nothing in the main thread, otherwise you risk to enter in a deadlock situation.

Installation

The recommended approach to use AwaitKit in your project is using the CocoaPods package manager, as it provides flexible dependency management and dead simple installation.

CocoaPods

Install CocoaPods if not already available:

$ [sudo] gem install cocoapods
$ pod setup

Go to the directory of your Xcode project, and Create and Edit your Podfile and add AwaitKit:

$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
pod 'AwaitKit', '~> 5.2.0'

Install into your project:

$ pod install

If CocoaPods did not find the PromiseKit 6.10 dependency execute this command:

$ pod repo update

Open your project in Xcode from the .xcworkspace file (not the usual project file)

$ open MyProject.xcworkspace

Swift Package Manager

You can use The Swift Package Manager to install AwaitKit by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .Package(url: "https://github.com/yannickl/AwaitKit.git")
    ]
)

Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate AwaitKit into your Xcode project using Carthage, specify it in your Cartfile:

github "yannickl/AwaitKit" ~> 5.2.0

Run carthage update to build the framework and drag the built AwaitKit.framework into your Xcode project.

Manually

Download the project and copy the AwaitKit folder into your project to use it in. Note that you also need to download the PromiseKit v6.7 library and import it to your project.

Contribution

Contributions are welcomed and encouraged ♡.

Contact

Yannick Loriot

License (MIT)

Copyright (c) 2016-present - Yannick Loriot

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

DynamicColor

Yet another extension to manipulate colors easily in Swift and SwiftUI
Swift
2,971
star
2

QRCodeReader.swift

Simple QRCode reader in Swift
Swift
1,315
star
3

YLProgressBar

UIProgressView replacement with an highly and fully customizable animated progress bar in pure Core Graphics
Objective-C
1,275
star
4

DynamicButton

Yet another animated flat buttons in Swift
Swift
1,168
star
5

Splitflap

A simple split-flap display for your Swift applications
Swift
1,074
star
6

FlowingMenu

Interactive view transition to display menus with flowing and bouncing effects in Swift
Swift
974
star
7

YLMoment

Parsing, validating, manipulating, and formatting dates easily in Objective-C (API inspired by moment.js)
Objective-C
709
star
8

QRCodeReaderViewController

Simple QRCode reader for iOS 7 and over
Objective-C
629
star
9

Reactions

Fully customizable Facebook reactions like control
Swift
584
star
10

SnappingStepper

An elegant alternative to the UIStepper written in Swift
Swift
429
star
11

Perspective

Powerful scrolling and motion parallax for iOS
Swift
266
star
12

CCControlExtension

Collection of classes to make the design of controls easier for Cocos2d-for-iPhone
Objective-C
209
star
13

Box2D-Examples

Box2D examples (Ragdoll, Buoyancy, etc.) for Cocos2D for iPhone
Objective-C
69
star
14

Petal

Beautiful activity indicator to show that a task is in progress
Swift
67
star
15

YLFlowingMenu

The Objective-C counterpart of FlowingMenu
Objective-C
28
star
16

YLTCPBroadcaster

Fast and easy-to-use network scanner to locate every host with a given open port
Objective-C
18
star
17

DynamicFont

Yet another extension to manipulate fonts easily in Swift
Swift
8
star
18

VLCRemoteKit

Remote control for VLC using the HTTP interface in Swift (Under Development)
Swift
3
star
19

Cocarde

Under development
Swift
1
star
20

RSSReaderDemonstrationApp

RSS Reader application for education purpose
Objective-C
1
star