From c693b525beda8c98f23967291be9a781b7bfd93b Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Fri, 25 Apr 2025 16:23:53 -0700 Subject: [PATCH] First commit --- .gitignore | 8 ++ License.md | 7 ++ Package.swift | 25 ++++++ Readme.md | 83 ++++++++++++++++++ .../AsyncMonitor/AnyAsyncCancellable.swift | 27 ++++++ Sources/AsyncMonitor/AsyncCancellable.swift | 11 +++ Sources/AsyncMonitor/AsyncMonitor.swift | 37 ++++++++ .../AsyncSequence+Extensions.swift | 19 ++++ Sources/AsyncMonitor/NSObject+AsyncKVO.swift | 20 +++++ .../AsyncMonitorTests/AsyncMonitorTests.swift | 86 +++++++++++++++++++ Tests/AsyncMonitorTests/ReadmeExamples.swift | 26 ++++++ 11 files changed, 349 insertions(+) create mode 100644 .gitignore create mode 100644 License.md create mode 100644 Package.swift create mode 100644 Readme.md create mode 100644 Sources/AsyncMonitor/AnyAsyncCancellable.swift create mode 100644 Sources/AsyncMonitor/AsyncCancellable.swift create mode 100644 Sources/AsyncMonitor/AsyncMonitor.swift create mode 100644 Sources/AsyncMonitor/AsyncSequence+Extensions.swift create mode 100644 Sources/AsyncMonitor/NSObject+AsyncKVO.swift create mode 100644 Tests/AsyncMonitorTests/AsyncMonitorTests.swift create mode 100644 Tests/AsyncMonitorTests/ReadmeExamples.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0023a53 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +/.build +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/configuration/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc diff --git a/License.md b/License.md new file mode 100644 index 0000000..1f05728 --- /dev/null +++ b/License.md @@ -0,0 +1,7 @@ +Copyright © 2025 Sami Samhuri, https://samhuri.net + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..f47af98 --- /dev/null +++ b/Package.swift @@ -0,0 +1,25 @@ +// swift-tools-version: 6.0 + +import PackageDescription + +let package = Package( + name: "AsyncMonitor", + platforms: [ + .iOS(.v17), + .macOS(.v15), + ], + products: [ + .library( + name: "AsyncMonitor", + targets: ["AsyncMonitor"]), + ], + targets: [ + .target( + name: "AsyncMonitor" + ), + .testTarget( + name: "AsyncMonitorTests", + dependencies: ["AsyncMonitor"] + ), + ] +) diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..ee3ea3c --- /dev/null +++ b/Readme.md @@ -0,0 +1,83 @@ +# AsyncMonitor + +[![0 dependencies!](https://0dependencies.dev/0dependencies.svg)](https://0dependencies.dev) +[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fsamsonjs%2FAsyncMonitor%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/samsonjs/AsyncMonitor) +[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fsamsonjs%2FAsyncMonitor%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/samsonjs/AsyncMonitor) + +## Overview + +AsyncMonitor is a Swift library that provides a simple and easy-to-use way to manage Swift concurrency `Task`s that observe async sequences. The `AsyncMonitor` class allows you to create tasks that observe streams and call the given closure with each new value, and optionally also with a context parameter so you don't have to manage its lifetime. + +It uses a Swift `Task` to ensure that all resources are properly cleaned up when the `AsyncMonitor` is cancelled or deallocated. + +That's it. It's pretty trivial. I just got tired of writing it over and over, mainly for notifications. You still have to map your `Notification`s to something sendable. + +## Installation + +The only way to install this package is with Swift Package Manager (SPM). Please [file a new issue][] or submit a pull-request if you want to use something else. + +[file a new issue]: https://github.com/samsonjs/AsyncMonitor/issues/new + +### Supported Platforms + +This package is supported on iOS 18.0+ and macOS 15.0+. + +### Xcode + +When you're integrating this into an app with Xcode then go to your project's Package Dependencies and enter the URL `https://github.com/samsonjs/AsyncMonitor` and then go through the usual flow for adding packages. + +### Swift Package Manager (SPM) + +When you're integrating this using SPM on its own then add this to the list of dependencies your Package.swift file: + +```swift +.package(url: "https://github.com/samsonjs/AsyncMonitor.git", .upToNextMajor(from: "0.1.0")) +``` + +and then add `"AsyncMonitor"` to the list of dependencies in your target as well. + +## Usage + +The simplest example uses a closure that receives the notification: + +```swift +import AsyncMonitor + +@MainActor class SimplestVersion { + let cancellable = NotificationCenter.default + .notifications(named: .NSCalendarDayChanged).map(\.name) + .monitor { _ in + print("The date is now \(Date.now)") + } +} +``` + +This example uses the context parameter to avoid reference cycles with `self`: + +```swift +import AsyncMonitor + +@MainActor class WithContext { + var cancellables = Set() + + init() { + NotificationCenter.default + .notifications(named: .NSCalendarDayChanged).map(\.name) + .monitor(context: self) { _self, _ in + _self.dayChanged() + }.store(in: &cancellables) + } + + func dayChanged() { + print("The date is now \(Date.now)") + } +} +``` + +The closure is async so you can await in there if you need to. + +## License + +Copyright © 2025 [Sami Samhuri](https://samhuri.net) . Released under the terms of the [MIT License][MIT]. + +[MIT]: https://sjs.mit-license.org diff --git a/Sources/AsyncMonitor/AnyAsyncCancellable.swift b/Sources/AsyncMonitor/AnyAsyncCancellable.swift new file mode 100644 index 0000000..1d6e1c0 --- /dev/null +++ b/Sources/AsyncMonitor/AnyAsyncCancellable.swift @@ -0,0 +1,27 @@ +public class AnyAsyncCancellable: AsyncCancellable { + let canceller: () -> Void + + init(cancellable: AC) { + canceller = { cancellable.cancel() } + } + + deinit { + cancel() + } + + // MARK: AsyncCancellable conformance + + public func cancel() { + canceller() + } + + // MARK: Hashable conformance + + public static func == (lhs: AnyAsyncCancellable, rhs: AnyAsyncCancellable) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} diff --git a/Sources/AsyncMonitor/AsyncCancellable.swift b/Sources/AsyncMonitor/AsyncCancellable.swift new file mode 100644 index 0000000..55252bd --- /dev/null +++ b/Sources/AsyncMonitor/AsyncCancellable.swift @@ -0,0 +1,11 @@ +public protocol AsyncCancellable: Hashable { + func cancel() + + func store(in set: inout Set) +} + +public extension AsyncCancellable { + func store(in set: inout Set) { + set.insert(AnyAsyncCancellable(cancellable: self)) + } +} diff --git a/Sources/AsyncMonitor/AsyncMonitor.swift b/Sources/AsyncMonitor/AsyncMonitor.swift new file mode 100644 index 0000000..da4b14f --- /dev/null +++ b/Sources/AsyncMonitor/AsyncMonitor.swift @@ -0,0 +1,37 @@ +public final class AsyncMonitor: Hashable, AsyncCancellable { + let task: Task + + public init( + isolation: isolated (any Actor)? = #isolation, + sequence: any AsyncSequence, + performing block: @escaping (Element) async -> Void + ) { + self.task = Task { + _ = isolation // use capture trick to inherit isolation + + for await element in sequence { + await block(element) + } + } + } + + deinit { + cancel() + } + + // MARK: AsyncCancellable conformance + + public func cancel() { + task.cancel() + } + + // MARK: Hashable conformance + + public static func == (lhs: AsyncMonitor, rhs: AsyncMonitor) -> Bool { + lhs.task == rhs.task + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(task) + } +} diff --git a/Sources/AsyncMonitor/AsyncSequence+Extensions.swift b/Sources/AsyncMonitor/AsyncSequence+Extensions.swift new file mode 100644 index 0000000..97a4e02 --- /dev/null +++ b/Sources/AsyncMonitor/AsyncSequence+Extensions.swift @@ -0,0 +1,19 @@ +public extension AsyncSequence where Element: Sendable, Failure == Never { + func monitor( + isolation: isolated (any Actor)? = #isolation, + _ block: @escaping (Element) async -> Void + ) -> AsyncMonitor { + AsyncMonitor(isolation: isolation, sequence: self, performing: block) + } + + func monitor( + isolation: isolated (any Actor)? = #isolation, + context: Context, + _ block: @escaping (Context, Element) async -> Void + ) -> AsyncMonitor { + AsyncMonitor(isolation: isolation, sequence: self) { [weak context] element in + guard let context else { return } + await block(context, element) + } + } +} diff --git a/Sources/AsyncMonitor/NSObject+AsyncKVO.swift b/Sources/AsyncMonitor/NSObject+AsyncKVO.swift new file mode 100644 index 0000000..50ce00f --- /dev/null +++ b/Sources/AsyncMonitor/NSObject+AsyncKVO.swift @@ -0,0 +1,20 @@ +public import Foundation + +extension KeyPath: @unchecked @retroactive Sendable where Value: Sendable {} + +public extension NSObjectProtocol where Self: NSObject { + func values( + for keyPath: KeyPath, + options: NSKeyValueObservingOptions = [], + changeHandler: @escaping @MainActor (Value) -> Void + ) -> any AsyncCancellable { + let (stream, continuation) = AsyncStream.makeStream() + let token = self.observe(keyPath, options: options) { object, _ in + continuation.yield(object[keyPath: keyPath]) + } + return stream.monitor { @MainActor value in + _ = token // keep this alive + changeHandler(value) + } + } +} diff --git a/Tests/AsyncMonitorTests/AsyncMonitorTests.swift b/Tests/AsyncMonitorTests/AsyncMonitorTests.swift new file mode 100644 index 0000000..c219bde --- /dev/null +++ b/Tests/AsyncMonitorTests/AsyncMonitorTests.swift @@ -0,0 +1,86 @@ +import Foundation +import Testing +@testable import AsyncMonitor + +@MainActor class AsyncMonitorTests { + let center = NotificationCenter() + let name = Notification.Name("a random notification") + + private var subject: AsyncMonitor? + + @Test func callsBlockWhenNotificationsArePosted() async throws { + await withCheckedContinuation { [center, name] continuation in + subject = center.notifications(named: name).map(\.name).monitor { receivedName in + #expect(name == receivedName) + continuation.resume() + } + Task { + center.post(name: name, object: nil) + } + } + } + + @Test func doesNotCallBlockWhenOtherNotificationsArePosted() async throws { + subject = center.notifications(named: name).map(\.name).monitor { receivedName in + Issue.record("Called for irrelevant notification \(receivedName)") + } + Task { + center.post(name: Notification.Name("something else"), object: nil) + } + try await Task.sleep(for: .milliseconds(10)) + } + + @Test func stopsCallingBlockWhenDeallocated() async throws { + subject = center.notifications(named: name).map(\.name).monitor { _ in + Issue.record("Called after deallocation") + } + + Task { + subject = nil + center.post(name: name, object: nil) + } + + try await Task.sleep(for: .milliseconds(10)) + } + + class Owner { + let deinitHook: () -> Void + + private var cancellable: (any AsyncCancellable)? + + @MainActor init(center: NotificationCenter, deinitHook: @escaping () -> Void) { + self.deinitHook = deinitHook + let name = Notification.Name("irrelevant name") + cancellable = center.notifications(named: name).map(\.name) + .monitor(context: self) { _, _ in } + } + + deinit { + deinitHook() + } + } + + private var owner: Owner? + + @Test(.timeLimit(.minutes(1))) func doesNotCreateReferenceCyclesWithContext() async throws { + await withCheckedContinuation { continuation in + self.owner = Owner(center: center) { + continuation.resume() + } + self.owner = nil + } + } + + @Test func stopsCallingBlockWhenContextIsDeallocated() async throws { + var context: NSObject? = NSObject() + subject = center.notifications(named: name).map(\.name) + .monitor(context: context!) { context, receivedName in + Issue.record("Called after context was deallocated") + } + context = nil + Task { + center.post(name: name, object: nil) + } + try await Task.sleep(for: .milliseconds(10)) + } +} diff --git a/Tests/AsyncMonitorTests/ReadmeExamples.swift b/Tests/AsyncMonitorTests/ReadmeExamples.swift new file mode 100644 index 0000000..f691053 --- /dev/null +++ b/Tests/AsyncMonitorTests/ReadmeExamples.swift @@ -0,0 +1,26 @@ +import Foundation +@testable import AsyncMonitor + +@MainActor class SimplestVersion { + let cancellable = NotificationCenter.default + .notifications(named: .NSCalendarDayChanged).map(\.name) + .monitor { _ in + print("The date is now \(Date.now)") + } +} + +@MainActor class WithContext { + var cancellables = Set() + + init() { + NotificationCenter.default + .notifications(named: .NSCalendarDayChanged).map(\.name) + .monitor(context: self) { _self, _ in + _self.dayChanged() + }.store(in: &cancellables) + } + + func dayChanged() { + print("The date is now \(Date.now)") + } +}