The easiest way to observe values in Swift.
Clone or download
roberthein Merge pull request #12 from 4brunu/feature/thread_safety
Add thread safety to Observable.value
Latest commit 5137813 Nov 12, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Example Small cleanup. Nov 8, 2018
Observable/Classes add Lock to uniqueID and Observers Nov 12, 2018
art Update to Swift 4. Sep 26, 2017
.gitignore Initial commit Aug 16, 2017
.swift-version Add swift version. Aug 18, 2017
.travis.yml Initial commit Aug 16, 2017
LICENSE Initial commit. Aug 16, 2017
Observable.podspec Bump version number. Nov 8, 2018
README.md fix typo Nov 8, 2018
_Pods.xcodeproj Initial commit Aug 16, 2017

README.md

Observable

Observable is the easiest way to observe values in Swift.

How to

Create an Observable

var position = Observable(CGPoint.zero)

Create Observer and ImmutableObserver

var position = Observable(CGPoint.zero)
var immutablePosition: ImmutableObservable<CGPoint> = position 
// With an ImmutableObservable the value can't be changed, only read or observe it's value changes

Add an observer

position.observe { p in
    // handle new position
}

Add an observer and specify the DispatchQueue

position.observe(DispatchQueue.main) { p in
// handle new position
}

Change the value

position.value = p

Memory management

For a single observer you can store the returned Disposable to a variable

disposable = position.observe { p in

For multiple observers you can add the disposable to a Disposal variable

position.observe { }.add(to: &disposal)

And always weakify self when referencing self inside your observer

position.observe { [weak self] position in

Installation

CocoaPods

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

pod 'Observable'

Carthage

Observable is available through Carthage. To install it, simply add the following line to your Cartfile:

github "roberthein/Observable" "master"

Suggestions or feedback?

Feel free to create a pull request, open an issue or find me on Twitter.