Giter Site home page Giter Site logo

signals's Introduction

Signals

Build Status Cocoapods Compatible Carthage Compatible License Platform Twitter

Signals is a library for creating and observing events. It replaces delegates, actions and NSNotificationCenter with something much more powerful and elegant.

Features

  • Attach-and-forget observation
  • Type-safety
  • Filtered observation
  • Delayed and queued observation
  • Comprehensive Unit Test Coverage

Requirements

  • iOS 7.0 / watchOS 2.0 / Mac OS X 10.9
  • Xcode 7.0 (compatible with Swift 2.0)

Installation

To use Signals with a project targeting iOS 7, simply copy Signals.swift into your project.

CocoaPods

To integrate Signals into your project add the following to your Podfile:

platform :ios, '8.0'
use_frameworks!

pod 'Signals', '~> 2.0'

Carthage

To integrate Signals into your project using Carthage add the following to your Cartfile:

github "artman/Signals" ~> 2.0

Quick start

Make events on a class observable by creating one or more signals:

class NetworkLoader {

    // Creates a number of signals that can be subscribed to
    let onData = Signal<(data:NSData, error:NSError)>()
    let onProgress = Signal<Float>()

    ...

    func receivedData(receivedData:NSData, receivedError:NSError) {
        // Whenever appropriate, fire off any of the signals
        self.onProgress.fire(1.0)
        self.onData.fire((data:receivedData, error:receivedError))
    }
}

Subscribe to these signals from elsewhere in your application

let networkLoader = NetworkLoader("http://artman.fi")

networkLoader.onProgress.listen(self) { (progress) in
    println("Loading progress: \(progress*100)%")
}

networkLoader.onData.listen(self) { (data, error) in
    // Do something with the data
}

Adding listeners to signals is a attach-and-forget operation. If your listener is deallocated, the Signal removes the listener from it's list of listeners. If the Signal emitter is deallocated, so is the closure that was supposed to fire on the listener, so you don't need to explicitly manage the removal of listeners.

Singals aren't restricted to one listener, so multiple objects can listen on the same Signal.

You can also subscribe to events after they have occurred:

networkLoader.onProgress.listenPast(self) { (progress) in
    // This will immediately fire with last progress that was reported
    // by the onProgress signal
    println("Loading progress: \(progress*100)%")
}

Advanced topics

Signal listeners can apply filters:

networkLoader.onProgress.listen(self) { (progress) in
    // This fires when progress is done
}.filter { $0 == 1.0 }

You can queue up listener dispatches for a set amount of time and fire them only once:

networkLoader.onProgress.listen(self) { (progress) in
    // Executed once per second while progress changes
}.queueAndDelayBy(1.0)

A signal dispatches listener calls synchronously on the posting thread by default. To define the thread explicitly, you should use the dispatchOnQueue method. In this way you will receive listener calls asynchronously on the specified queue:

networkLoader.onProgress.listen(self) { (progress) in
    // This fires on the main queue
}.dispatchOnQueue(dispatch_get_main_queue())

If you don't like the double quotes that you have to use since Swift 2.0 when you fire signals that take tuples, you can use a special operator to fire the data:

// If you don't like the double quotes when firing signals that have tuples
self.onData.fire((data:receivedData, error:receivedError))

// You can use the => operator to fire the signal
self.onData => (data:receivedData, error:receivedError)
  
// Also works for signals without tuples
self.onProgress => 1.0

Replacing actions

Signals extends all classes that extend from UIControl (not available on OS X) and lets you use signals to listen to control events for increased code locality.

let button = UIButton()
button.onTouchUpInside.listen(self) {
    // Handle the touch
}

let slider = UISlider()
slider.onValueChanged.listen(self) {
    // Handle value change
}

Replacing delegates

Signals is simple and modern and greatly reduce the amount of boilerplate that is required to set up delegation.

Would you rather implement a callback using a delegate:

  • Create a protocol that defines what is delegated
  • Create a delegate property on the class that wants to provide delegation
  • Mark each class that wants to become a delegate as comforming to the delegate protocol
  • Implement the delegate methods on the class that want to become a delegate
  • Set the delegate property to become a delegate of the instance
  • Check that your delegate implements each delegate method before invoking it

Or do the same thing with Signals:

  • Create a signal for the class that wants to provide an event
  • Subscribe to the signal as a listener from any instance you want

Signals can have multiple listeners and they therefore don't provide a way for the observer to return data to the signal invoker. The delegate pattern should still be used for data requests (e.g. UITableViewDataSource).

Replace NSNotificationCenter

To replace global notifications via the NSNotificationCenter with Signals, just create a Singleton with a number of public signals that anybody can subscribe to or fire. You'll gain type safety, refactorability and attach-and-forget observation.

Communication

  • If you found a bug, open an issue or submit a fix via a pull request.
  • If you have a feature request, open an issue or submit a implementation via a pull request or hit me up on Twitter @artman
  • If you want to contribute, submit a pull request onto the development branch.

License

Signals is released under an MIT license. See the LICENSE file for more information

signals's People

Contributors

artman avatar sgl0v avatar reneb avatar robskillington avatar christiansteffens avatar netizen01 avatar raj-room avatar

Watchers

James Cloos avatar

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.