Member-only story
In this story we’ll go over the basic of Combine and how to use it to improve your codebase. Combine is a functional reactive library introduced by Apple. Similar libraries created by the Swift community such as RxCocoa and ReactiveSwift have existed for awhile. If you haven’t heard of functional reactive programming don’t worry, it’s not as complicated as it sounds.
Observable Pattern
Understanding the observable pattern is a good building block for understanding how Combine works. The Observable pattern is used for notifying an object when a mutation has occurred. It similar to the Subscriber/Publisher, KVO and NotificationCenter in iOS.
struct User {
let numberOfFollowing: Int
let numberOfFollower: Int
}protocol Observable {
func observe(_ onUpdate: @escaping () -> Void)
}class UserStore: Observable { func observe(_ onUpdate: @escaping () -> Void) {
// Store the observer
observables.append(onUpdate)
} private(set) var observables: [() -> Void] = []}
Observable in Combine
class UserStore {
// Notifies the object of when the user is updated.
let objectWillChange = ObjectWillChangePublisher()
}class FollowingController: UIViewController {
let store: UserStore func viewDidLoad() {
super.viewDidLoad()
store.objectWillChange.sink {
} }}