• Stars
    star
    217
  • Rank 176,433 (Top 4 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 7 years ago

Reviews

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

Repository Details

Operation Oriented Programming in Swift

Flow

Travis CocoaPods Carthage

Flow is a lightweight Swift library for doing operation oriented programming. It enables you to easily define your own, atomic operations, and also contains an exensive library of ready-to-use operations that can be grouped, sequenced, queued and repeated.

Operations

Using Flow is all about splitting your code up into multiple atomic pieces - called operations. Each operation defines a body of work, that can easily be reused throughout an app or library.

An operation can do anything, synchronously or asynchronously, and its scope is really up to you. The true power of operation oriented programming however, comes when you create groups, sequences and queues out of operations. Operations can potentially make code that is either asynchronous, or where work has to be done in several places, a lot simpler.

How to use

  • Create your own operations by conforming to FlowOperation in a custom object. All it needs to do it implement one method that performs it with a completion handler. It’s free to be initialized in whatever way you want, and can be either a class or a struct.

  • Use any of the built-in operations, such as FlowClosureOperation, FlowDelayOperation, etc.

  • Create sequences of operations (that get executed one by one) using FlowOperationSequence, groups (that get executed all at once) using FlowOperationGroup, or queues (that can be continuously filled with operations) using FlowOperationQueue.

Example

Let’s say we’re building a game and we want to perform a series of animations where a Player attacks an Enemy, destroys it and then plays a victory animation. This could of course be accomplished with the use of completion handler closures:

player.moveTo(enemy.position) {
    player.performAttack() {
        enemy.destroy() {
            player.playVictoryAnimation()
        }
    }
}

However, this quickly becomes hard to reason about and debug, especially if we start adding multiple animations that we want to sync. Let’s say we decide to implement a new spin attack in our game, that destroys multiple enemies, and we want all enemies to be destroyed before we play the victory animation. We’d have to do something like this:

player.moveTo(mainEnemy.position) {
    player.performAttack() {
        var enemiesDestroyed = 0
                
        for enemy in enemies {
            enemy.destroy({
                enemiesDestroyed += 1
                        
                if enemiesDestroyed == enemies.count {
                    player.playVictoryAnimation()
                }
            })
        }
    }
}

It becomes clear that the more we add to our animation, the more error prone and hard to debug it becomes. Wouldn’t it be great if our animations (or any other sequence of tasks) could scale gracefully as we make them more and more complex?

Let’s implement the above using Flow instead. We’ll start by defining all tasks that we need to perform during our animation as operations:

/// Operation that moves a Player to a destination
class PlayerMoveOperation: FlowOperation {
    private let player: Player
    private let destination: CGPoint
    
    init(player: Player, destination: CGPoint) {
        self.player = player
        self.destination = destination
    }
    
    func perform(completionHandler: @escaping () -> Void) {
        self.player.moveTo(self.destination, completionHandler: completionHandler)
    }
}

/// Operation that performs a Player attack
class PlayerAttackOperation: FlowOperation {
    private let player: Player
    
    init(player: Player) {
        self.player = player
    }
    
    func perform(completionHandler: @escaping () -> Void) {
        self.player.performAttack(completionHandler)
    }
}

/// Operation that destroys an enemy
class EnemyDestroyOperation: FlowOperation {
    private let enemy: Enemy
    
    init(enemy: Enemy) {
        self.enemy = enemy
    }
    
    func perform(completionHandler: @escaping () -> Void) {
        self.enemy.destroy(completionHandler)
    }
}

/// Operation that plays a Player victory animation
class PlayerVictoryOperation: FlowOperation {
    private let player: Player
    
    init(player: Player) {
        self.player = player
    }
    
    func perform(completionHandler: @escaping () -> Void) {
        self.player.playVictoryAnimation()
        completionHandler()
    }
}

Secondly; we’ll implement our animation using the above operations:

let moveOperation = PlayerMoveOperation(player: player, destination: mainEnemy.position)
let attackOperation = PlayerAttackOperation(player: player)
let destroyEnemiesOperation = FlowOperationGroup(operations: enemies.map({
    return EnemyDestroyOperation(enemy: $0)
}))
let victoryOperation = PlayerVictoryOperation(player: player)
        
let operationSequence = FlowOperationSequence(operations: [
    moveOperation,
    attackOperation,
    destroyEnemiesOperation,
    victoryOperation
])
        
operationSequence.perform()

While we had to write a bit more code using operations; this approach has some big advantages.

Firstly; we can now use a FlowOperationGroup to make sure that all enemy animations are finished before moving on, and by doing this we’ve reduced the state we need to keep within the animation itself.

Secondly; all parts of the animation are now independant operations that don’t have to be aware of each other, making them a lot easier to test & debug - and they could also be reused in other parts of our game.

API reference

Protocols

FlowOperation Used to declare custom operations.

FlowOperationCollection Used to declare custom collections of operations.

Base operations

FlowClosureOperation Operation that runs a closure, and returns directly when performed.

FlowAsyncClosureOperation Operation that runs a closure, then waits for that closure to call a completion handler before it finishes.

FlowDelayOperation Operation that waits for a certain delay before finishing. Useful in sequences and queues.

Operation collections & utilities

FlowOperationGroup Used to group together a series of operations that all get performed at once when the group is performed.

FlowOperationSequence Used to sequence a series of operations, performing them one by one once the sequence is performed.

FlowOperationQueue Queue that keeps executing the next operation as soon as it becomes idle. New operations can constantly be added.

FlowOperationRepeater Used to repeat operations, optionally using an interval in between repeats.

How is this different from NSOperations?

NSOperations are awesome - and are definetly one of the main sources of inspiration for Flow. However, NSOperations are quite heavyweight and can potentially take a long time to implement. Flow was designed to have the power of NSOperations, but be a lot easier to use. It’s also written 100% using Swift - making it ideal for Swift-based projects.

Compatibility

Flow supports all current Apple platforms with the following minimum versions:

  • iOS 8
  • macOS 10.11
  • watchOS 2
  • tvOS 9

The current version of Flow supports Swift 3. If you need Swift 2 support, either use version 1.1, or the swift 2 branch.

Installation

CocoaPods:

Add the line pod "FlowOperations" to your Podfile

Carthage:

Add the line github "johnsundell/flow" to your Cartfile

Manual:

Clone the repo and drag the file Flow.swift into your Xcode project.

Swift Package Manager:

Add the line .Package(url: "https://github.com/johnsundell/flow.git", majorVersion: 2) to your Package.swift

Hope you enjoy using Flow!

For support, feedback & news about Flow; follow me on Twitter: @johnsundell.

More Repositories

1

Publish

A static site generator for Swift developers
Swift
4,763
star
2

SwiftTips

A collection of Swift tips & tricks that I've shared on Twitter
3,971
star
3

Files

A nicer way to handle files & folders in Swift
Swift
2,456
star
4

Ink

A fast and flexible Markdown parser written in Swift.
Swift
2,336
star
5

Unbox

[Deprecated] The easy to use Swift JSON decoder
Swift
1,956
star
6

Plot

A DSL for writing type-safe HTML, XML and RSS in Swift.
Swift
1,946
star
7

Marathon

[DEPRECATED] Marathon makes it easy to write, run and manage your Swift scripts 🏃
Swift
1,869
star
8

ImagineEngine

A project to create a blazingly fast Swift game engine that is a joy to use 🚀
Swift
1,818
star
9

SwiftPlate

Easily generate cross platform Swift framework projects from the command line
Swift
1,766
star
10

Splash

A fast, lightweight and flexible Swift syntax highlighter for blogs, tools and fun!
Swift
1,735
star
11

TestDrive

Quickly try out any Swift pod or framework in a playground
Swift
1,597
star
12

Codextended

Extensions giving Swift's Codable API type inference super powers 🦸‍♂️🦹‍♀️
Swift
1,488
star
13

ShellOut

Easily run shell commands from a Swift script or command line tool
Swift
836
star
14

Wrap

[DEPRECATED] The easy to use Swift JSON encoder
Swift
732
star
15

CollectionConcurrencyKit

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.
Swift
730
star
16

Sweep

Fast and powerful Swift string scanning made simple
Swift
531
star
17

Playground

Instantly create Swift playgrounds from the command line
Swift
439
star
18

Require

Require optional values to be non-nil, or crash gracefully
Swift
414
star
19

XcodeTheme

My Xcode theme - Sundell's Colors
Swift
408
star
20

AsyncCompatibilityKit

iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.
Swift
377
star
21

Shapeshift

Quickly convert a folder containing Swift files into an iPad-compatible Playground
Swift
339
star
22

Identity

🆔 Type-safe identifiers in Swift
Swift
298
star
23

SwiftBySundell

Code samples from the Swift by Sundell website & podcast
Swift
289
star
24

SwiftScripting

A list of Swift scripting tools, frameworks & examples
235
star
25

SuperSpriteKit

Extensions to Apple's SpriteKit game engine
Objective-C
224
star
26

Xgen

A Swift package for generating Xcode workspaces & playgrounds
Swift
189
star
27

IndieSupportWeeks

A two-week effort to help support indie developers shipping apps on Apple's platforms who have been financially impacted by the COVID-19 pandemic.
183
star
28

CGOperators

Easily manipulate CGPoints, CGSizes and CGVectors using math operators
Swift
148
star
29

Animate

Declarative UIView animations without nested closures
Swift
129
star
30

SplashPublishPlugin

A Splash plugin for the Publish static site generator
Swift
92
star
31

Assert

A collection of convenient assertions for Swift testing
Swift
69
star
32

UITestingExample

Example code from my blog post about UI testing
Swift
67
star
33

Marathon-Examples

A collection of example Swift scripts that can easily be run using Marathon
Swift
55
star
34

Releases

A Swift package for resolving released versions from a Git repository
Swift
51
star
35

BlockSnippets

Xcode snippets that are very handy when working with blocks in various contexts
51
star
36

PlotPlayground

A Swift playground that comes pre-loaded with Plot, that can be used to explore the new component API.
Swift
49
star
37

SwiftKit

A collection of Swift utilities that I share across my Swift-based projects
Swift
38
star
38

UnitTestingWorkshop

Project used during my workshop "Getting started with unit testing in Swift"
Swift
36
star
39

JSUpdateLookup

A lightweight, easy to use Objective-C class to check if your iOS app has an update available
Objective-C
28
star
40

SwiftAveiro

Skeleton project for my Swift Aveiro workshop "Everyone is an API designer"
Swift
15
star
41

CloudKitChat

A demo chat application powered by CloudKit
Objective-C
14
star
42

swiftbysundell-beta-feedback

Submit your feedback on the Swift by Sundell 2.0 beta
9
star
43

JSGeometry

A set of utility functions that enables easy one-line manipulation of CoreGraphics geometry structs like CGPoint, CGSize & CGRect.
Objective-C
6
star
44

JSAutoCopy

An Objective-C category that enables automatic copying of any object
Objective-C
4
star
45

UnboxDemoPlayground

A Swift Playground that comes setup with Unbox & Wrap, used in my CocoaHeads Stockholm presentation
Swift
3
star
46

JSAutoEncodedObject

Automatically encode or decode any Objective-C object
Objective-C
3
star
47

JSLocalization

An Objective-C class that enables dynamic localization of an iOS app.
Objective-C
3
star
48

MarathonTestScriptWithDependencies

A test script with dependencies - used for Marathon's tests
Swift
2
star
49

JSObservableObject

Easily add protocol-based observation to any Objective-C class
Objective-C
2
star
50

MarathonTestPackage

A Swift package that's used in Marathon's tests
Swift
1
star
51

MarathonTestScript

A Swift script that's used in Marathon's tests
Swift
1
star