diff --git a/Excitation/Excitation.swift b/Excitation/Excitation.swift index 351c664..08d8035 100644 --- a/Excitation/Excitation.swift +++ b/Excitation/Excitation.swift @@ -45,7 +45,7 @@ public class Emitter { } public func observe(_ f: @escaping ()->Void) -> Observer { - return self.observe({ (_: T) in f() }) + return self.observe { (_: T) in f() } } public func observe(_ f: @escaping (T)->Void) -> Observer { let ob = Observer(f) @@ -55,6 +55,15 @@ public class Emitter { obRef[ObjectIdentifier(ob)] = ob return ob } + + public func observeAsync(_ f: @escaping ()->Void) -> Observer { + return self.observeAsync { (_: T) in f() } + } + public func observeAsync(_ f: @escaping (T)->Void) -> Observer { + return self.observe { data in + DispatchQueue.main.async { f(data) } + } + } public func remove(_ ob: Observer) { nc.removeObserver(ob, name: nn, object: nil) diff --git a/ExcitationTests/ExcitationTests.swift b/ExcitationTests/ExcitationTests.swift index 8fe5c6b..6466c50 100644 --- a/ExcitationTests/ExcitationTests.swift +++ b/ExcitationTests/ExcitationTests.swift @@ -33,4 +33,23 @@ class ExcitationTests: XCTestCase { e.remove(ob) e.emit() } + + func testAsyncNoData() { + let e = Emitter() + let ex = XCTestExpectation(description: "async event") + let _ = e.observeAsync { ex.fulfill() } + e.emit() + wait(for: [ex], timeout: 1) + } + + func testAsyncWithData() { + let e = Emitter() + let ex = XCTestExpectation(description: "async event") + let _ = e.observeAsync { n in + XCTAssert( n == 1 ) + ex.fulfill() + } + e.emit(1) + wait(for: [ex], timeout: 1) + } } diff --git a/README.md b/README.md index 65685f8..4c66961 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -A thin wrapper around NotificationCenter for supporting event-driven code. +A thin wrapper around `NotificationCenter` and `DispatchQueue` for supporting event-driven code. -Event handlers are dispatched synchronously as is NotificationCenter. +Excitation supports both sync and async events via `DispatchQueue.main`. ## Install @@ -37,12 +37,13 @@ e.observe { // Emit event e.emit() -// Example: Event with Data +// Example: Event with Data & Async // ===================================================== let e = Emitter() e.observe { n in print(n) } // prints 1 -e.observe { print("hi") } // prints hi +e.observe { print("hi") } +e.observeAsync { print("async handler") } e.emit(1) // Example: Remove Handlers