First commit

This commit is contained in:
Sami Samhuri 2025-04-25 16:23:53 -07:00
commit c693b525be
No known key found for this signature in database
11 changed files with 349 additions and 0 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc

7
License.md Normal file
View file

@ -0,0 +1,7 @@
Copyright © 2025 Sami Samhuri, https://samhuri.net <sami@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.

25
Package.swift Normal file
View file

@ -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"]
),
]
)

83
Readme.md Normal file
View file

@ -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<AnyAsyncCancellable>()
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) <sami@samhuri.net>. Released under the terms of the [MIT License][MIT].
[MIT]: https://sjs.mit-license.org

View file

@ -0,0 +1,27 @@
public class AnyAsyncCancellable: AsyncCancellable {
let canceller: () -> Void
init<AC: AsyncCancellable>(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))
}
}

View file

@ -0,0 +1,11 @@
public protocol AsyncCancellable: Hashable {
func cancel()
func store(in set: inout Set<AnyAsyncCancellable>)
}
public extension AsyncCancellable {
func store(in set: inout Set<AnyAsyncCancellable>) {
set.insert(AnyAsyncCancellable(cancellable: self))
}
}

View file

@ -0,0 +1,37 @@
public final class AsyncMonitor: Hashable, AsyncCancellable {
let task: Task<Void, Never>
public init<Element: Sendable>(
isolation: isolated (any Actor)? = #isolation,
sequence: any AsyncSequence<Element, Never>,
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)
}
}

View file

@ -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<Context: AnyObject>(
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)
}
}
}

View file

@ -0,0 +1,20 @@
public import Foundation
extension KeyPath: @unchecked @retroactive Sendable where Value: Sendable {}
public extension NSObjectProtocol where Self: NSObject {
func values<Value: Sendable>(
for keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
changeHandler: @escaping @MainActor (Value) -> Void
) -> any AsyncCancellable {
let (stream, continuation) = AsyncStream<Value>.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)
}
}
}

View file

@ -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))
}
}

View file

@ -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<AnyAsyncCancellable>()
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)")
}
}