Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add queue support and keypath support to ObserverSet #21

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
298 changes: 187 additions & 111 deletions ObserverSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,122 +26,198 @@
import Dispatch

/// A reference to an entry in the list of observers. Use this to remove an observer.
open class ObserverSetEntry<Parameters> {

public typealias ObserverCallback = (Any) -> (Parameters) -> Void

fileprivate weak var observer: AnyObject?
fileprivate let callBack: ObserverCallback

fileprivate init(observer: AnyObject?, callBack: @escaping ObserverCallback) {
self.observer = observer
self.callBack = callBack
}

}
public class ObserverSetEntry<Parameters> {

/// A set of observers that can be notified of certain actions. A more Swift-like version of NSNotificationCenter.
open class ObserverSet<Parameters> {

// MARK: - Private properties

private var entries: [ObserverSetEntry<Parameters>] = []

// MARK: - Initialisers

/**
Creates a new instance of an observer set.

- returns: A new instance of an observer set.
*/
public init() {}

// MARK: - Public functions

/**
Adds a new observer to the set.

- parameter observer: The object that is to be notified.
- parameter callBack: The function to call on the observer when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
open func add<ObserverType: AnyObject>(_ observer: ObserverType, _ callBack: @escaping (ObserverType) -> (Parameters) -> Void) -> ObserverSetEntry<Parameters> {
let entry = ObserverSetEntry<Parameters>(observer: observer) { observer in callBack(observer as! ObserverType) }
synchronized {
self.entries.append(entry)
}
return entry
}

/**
Adds a new function to the list of functions to invoke when a notification is to be delivered.

- parameter callBack: The function to call when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
open func add(_ callBack: @escaping (Parameters) -> Void) -> ObserverSetEntry<Parameters> {
return self.add(self) { ignored in callBack }
}

/**
Removes an observer from the list, using the entry which was returned when adding.

- parameter entry: An entry returned when adding a new observer.
*/
open func remove(_ entry: ObserverSetEntry<Parameters>) {
synchronized {
self.entries = self.entries.filter{ $0 !== entry }
}
}

fileprivate var isExpired: Bool { false }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current swift version for this repo is 4.0 so these one line implicit returns wont work yet.

Suggested change
fileprivate var isExpired: Bool { false }
fileprivate var isExpired: Bool { return false }


/**
Removes an observer from the list.
fileprivate func call(_ parameters: Parameters) {
// overridden

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think its worth putting an assertionFailure in here to indicate that it should be subclassed and overridden?

assertionFailure("Function should be overridden before being called")

}
}

- parameter observer: An observer to remove from the list of observers.
*/
open func removeObserver(_ observer: AnyObject) {
synchronized {
self.entries = self.entries.filter{ $0.observer !== observer }
}
}
private class ObserverSetEntryImpl<ObserverType: AnyObject, Parameters>: ObserverSetEntry<Parameters> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to name with ObserverSetEntry and have the above class called AnyObserverSetEntry, but naming it this way is more backwards compatible.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we name this something like DefaultObserverSetEntry instead? Impl doesn't read very well in my opinion


typealias ObserverCallback = (ObserverType) -> (Parameters) -> Void

private(set) weak var observer: ObserverType?
private let callBack: ObserverCallback
private let queue: DispatchQueue?

override var isExpired: Bool { observer == nil }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above

Suggested change
override var isExpired: Bool { observer == nil }
override var isExpired: Bool { return observer == nil }


init(queue: DispatchQueue?, observer: ObserverType, callBack: @escaping ObserverCallback) {
self.queue = queue
self.observer = observer
self.callBack = callBack
}

override func call(_ parameters: Parameters) {
if let observer = observer {
let callBack = self.callBack(observer)
if let queue = queue {
queue.async {
callBack(parameters)
}
} else {
callBack(parameters)
}
}
Comment on lines +55 to +64

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very minor. But might be cleaner to guard around observer rather than have these nester if let statements.

Suggested change
if let observer = observer {
let callBack = self.callBack(observer)
if let queue = queue {
queue.async {
callBack(parameters)
}
} else {
callBack(parameters)
}
}
guard let observer = observer else { return }
let callBack = self.callBack(observer)
if let queue = queue {
queue.async {
callBack(parameters)
}
} else {
callBack(parameters)
}

}

}

/**
Call this method to notify all observers.

- parameter parameters: The parameters that are required parameters specified using generics when the instance is created.
*/
open func notify(_ parameters: Parameters) {
var callBackList: [(Parameters) -> Void] = []
synchronized {
for entry in self.entries {
if let observer = entry.observer {
callBackList.append(entry.callBack(observer))
}
}
self.entries = self.entries.filter{ $0.observer != nil }
}
for callBack in callBackList {
callBack(parameters)
}
}

// MARK: - Private functions
// MARK: Locking support

private var queue = DispatchQueue(label: "com.theappbusiness.ObserverSet", attributes: [])

private func synchronized(_ f: () -> Void) {
queue.sync(execute: f)
}
/// A set of observers that can be notified of certain actions. A more Swift-like version of NSNotificationCenter.
open class ObserverSet<Parameters> {

// MARK: - Private properties

private var entries: [ObserverSetEntry<Parameters>] = []

// MARK: - Initialisers

/**
Creates a new instance of an observer set.

- returns: A new instance of an observer set.
*/
public init() {}

// MARK: - Public functions

/**
Adds a new observer to the set.

- parameter queue: The queue to call the function on when the notification is delivered. If nil (the default) it will be delivered on the same queue the notification was sent.
- parameter observer: The object that is to be notified.
- parameter callBack: The function to call on the observer when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
open func add<ObserverType: AnyObject>(queue: DispatchQueue? = nil, _ observer: ObserverType, _ callBack: @escaping (ObserverType) -> (Parameters) -> Void) -> ObserverSetEntry<Parameters> {
let entry = ObserverSetEntryImpl<ObserverType, Parameters>(queue: queue, observer: observer, callBack: callBack)
synchronized {
self.entries.append(entry)
}
return entry
}

/**
Adds a new function (or closure) to call when a notification is to be delivered.
This callback will be notified until it is removed by passing the return value to the `remove(_:)` method

The return value is not discardable as the callback should be removed manually. To attach it to the life cycle of an object, use the `add` method that takes a `lifeCycleObserver` parameter.

- parameter queue: The queue to call the function on when the notification is delivered. If nil (the default) it will be delivered on the same queue the notification was sent.
- parameter callBack: The function to call when the notification is to be delivered.

- returns: An entry in the list of observers, which should be used later to remove the observer.
*/
open func add(queue: DispatchQueue? = nil, _ callBack: @escaping (Parameters) -> Void) -> ObserverSetEntry<Parameters> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not 100% sure about this but it makes sense that this shouldn't be @discardableResult to prompt the user to remember to remove the observer at some point. If they really want it to be always added then they can do _ = observerSet.add(...) which I've had to do in some places in the Tesco App where we set up observers on app launch.

add(queue: queue, self) { _ in callBack }
}

/**
Adds a new function (or closure) to call when a notification is to be delivered.
The callback will be removed when the `lifeCycleObserver` object is deallocated

- parameter queue: The queue to call the function on when the notification is delivered. If nil (the default) it will be delivered on the same queue the notification was sent.
- parameter callBack: The function to call when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
open func add<ObserverType: AnyObject>(queue: DispatchQueue? = nil, _ lifeCycleObserver: ObserverType, _ callBack: @escaping (Parameters) -> Void) -> ObserverSetEntry<Parameters> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added this function for convenience when you want to use a closure but want to tie to the lifecycle of an object.

One use case is instead of this:

let someObserverSet = ObserverSet<Int>()
let someObserverSet = ObserverSet<String>()

class Foo {
  private let observer1: Any
  private let observer2: Any
  init() {
      // Use closures to ignore the parameters that are different
      observer1 = someObserverSet.add { [weak self] _ in self?.update() }
      observer2 = anotherObserverSet.add { [weak self] _ in self?.update() }
  }
  func update() {
  
  }
  deinit {
    someObserverSet.remove(observer1)
    someObserverSet.remove(observer2)
  }
}

Just do this:

class Foo {
  init() {
      // Use closures to ignore the parameters that are different
      someObserverSet.add(self) { [weak self] _ in self?.update() }
      anotherObserverSet.add(self) { [weak self] _ in self?.update() }
  }
  func update() {
  
  }
}

An alternative would be to allow observers that have no parameters for any ObserverSet that has a non void Parameters type, but that would remove some of the type safety.

class Foo {
  init() {
      // Use closures to ignore the parameters that are different
      someObserverSet.add(self, Foo.update)
      anotherObserverSet.add(self, Foo.update) // oops I meant to do Foo.bar which takes the parameter but there is no error because any () -> Void function can be used as a callback for any ObserverSet
  }
  func update() {
  
  }

  func bar(_: String) { }
}

add(queue: queue, lifeCycleObserver) { _ in callBack }
}

/**
Sets the keyPath on an observer to the value received when a notification is delivered.

- parameter queue: The queue to call the function on when the notification is delivered. If nil (the default) it will be delivered on the same queue the notification was sent.
- parameter keyPath: The keyPath to set when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
open func add<ObserverType: AnyObject>(queue: DispatchQueue? = nil, _ observer: ObserverType, _ keyPath: ReferenceWritableKeyPath<ObserverType, Parameters>) -> ObserverSetEntry<Parameters> {
add(queue: queue, observer) { observer in { observer[keyPath: keyPath] = $0 } }
}

/**
Removes an observer from the list, using the entry which was returned when adding.

- parameter entry: An entry returned when adding a new observer.
*/
open func remove(_ entry: ObserverSetEntry<Parameters>) {
synchronized {
self.entries = self.entries.filter{ $0 !== entry }
}
}


/**
Removes an observer from the list.

- parameter observer: An observer to remove from the list of observers.
*/
open func removeObserver<ObserverType: AnyObject>(_ observer: ObserverType) {
synchronized {
self.entries.removeAll(where: { ($0 as? ObserverSetEntryImpl<ObserverType, Parameters>)?.observer === observer })
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I switched to removeAll(where:) instead of filter because it reads better

}
}

/**
Call this method to notify all observers.

- parameter parameters: The parameters that are required parameters specified using generics when the instance is created.
*/
open func notify(_ parameters: Parameters) {
let callBackList = synchronized { () -> [ObserverSetEntry<Parameters>] in
self.entries.removeAll(where: { $0.isExpired })
return self.entries
}
for callBack in callBackList {
callBack.call(parameters)
}
}

// MARK: - Private functions
// MARK: Locking support

private var queue = DispatchQueue(label: "com.theappbusiness.ObserverSet", attributes: [])

private func synchronized<T>(_ f: () -> T) -> T {
queue.sync(execute: f)
}
}

public extension ObserverSet where Parameters == Void {
public func notify() {
notify(())
}

/**
Call this method to notify all observers.
*/
func notify() {
notify(())
}
/**
Adds a new observer to the set.

Convenience method so that the callback function can be `func callback() { ... }` instead of `func callback(_: Void) { ... }`

- parameter queue: The queue to call the function on when the notification is delivered. If nil (the default) it will be delivered on the same queue the notification was sent.
- parameter observer: The object that is to be notified.
- parameter callBack: The function to call on the observer when the notification is to be delivered.

- returns: An entry in the list of observers, which can be used later to remove the observer.
*/
@discardableResult
func add<ObserverType: AnyObject>(queue: DispatchQueue? = nil, _ observer: ObserverType, _ callBack: @escaping (ObserverType) -> () -> Void) -> ObserverSetEntry<Parameters> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't needed for the other adds as Swift seems to realise () -> Void and (Void) -> Void are the same thing

add(queue: queue, observer) { observer in
{ _ in
callBack(observer)()
}
}
}

}