Objective-C support was dropped in version 2.0.0
. If you need it, please use version 1.4.0
or lower.
Overview
Broadcast is a quick-and-dirty solution for instance syncing and property binding. Similar things can be achieved with libraries like ReactiveCocoa, but these are often overly-complicated and more robust than needed.
Installation
CocoaPods
Broadcast is integrated with CocoaPods!
- Add the following to your
Podfile
:
use_frameworks!
pod 'Broadcast'
- In your project directory, run
pod install
- Import the
Broadcast
module wherever you need it - Profit
Manually
You can also manually add the source files to your project.
- Clone this git repo
- Add all the Swift files in the
Broadcast/
subdirectory to your project - Profit
Broadcastable
The Broadcastable
protocol defines an object that can notify and react when property changes occur.
To conform to Broadcastable
, an object simply needs to return a broadcast identifier, and call broadcast.make()
when initialized.
This broadcast identifier will be used to identify matching instances and notify them of changes.
class Post: Broadcastable {
var postId: String
var numberOfLikes: Int
var broadcastId: String {
return postId
}
init(postId: String, numberOfLikes: Int) {
self.postId = postId
self.numberOfLikes = numberOfLikes
self.broadcast.make()
}
}
Signaling
Any changes made inside a signal block will be propagated to all instances of an object that share the same identifier.
The signal()
function's closure provides a "proxy" template object that will be swapped with the actual matching concrete Broadcastable
object
upon execution.
post.broadcast.signal { (aPost) in
aPost.numberOfLikes += 1
}
Listening
Broadcastable
objects can be externally observed for changes. This is extremely useful when you need to bind your UI to an object's properties.
class PostCell: UITableViewCell {
var listener: BroadcastListener?
var post: Post? {
didSet {
guard let post = post else { return }
layoutUI(with: post)
listener = post.broadcast.listen { [weak self] in
self?.layoutUI(with: post)
}
}
}
...
}
Groups of Broadcastable
objects can also be observed at once via BroadcastGroupListener
:
var listener: BroadcastGroupListener?
let posts = [
Post(postId: "0", numberOfLikes: 3),
Post(postId: "1", numberOfLikes: 13),
Post(postId: "2", numberOfLikes: 23)
]
listener = posts.listen { (object) in
print("A post was updated!")
}