Skip to content

Commit c693b52

Browse files
committed
First commit
0 parents  commit c693b52

File tree

11 files changed

+349
-0
lines changed

11 files changed

+349
-0
lines changed

.gitignore

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.DS_Store
2+
/.build
3+
/Packages
4+
xcuserdata/
5+
DerivedData/
6+
.swiftpm/configuration/registries.json
7+
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
8+
.netrc

License.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright © 2025 Sami Samhuri, https://samhuri.net <[email protected]>
2+
3+
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:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
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.

Package.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// swift-tools-version: 6.0
2+
3+
import PackageDescription
4+
5+
let package = Package(
6+
name: "AsyncMonitor",
7+
platforms: [
8+
.iOS(.v17),
9+
.macOS(.v15),
10+
],
11+
products: [
12+
.library(
13+
name: "AsyncMonitor",
14+
targets: ["AsyncMonitor"]),
15+
],
16+
targets: [
17+
.target(
18+
name: "AsyncMonitor"
19+
),
20+
.testTarget(
21+
name: "AsyncMonitorTests",
22+
dependencies: ["AsyncMonitor"]
23+
),
24+
]
25+
)

Readme.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# AsyncMonitor
2+
3+
[![0 dependencies!](https://0dependencies.dev/0dependencies.svg)](https://0dependencies.dev)
4+
[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fsamsonjs%2FAsyncMonitor%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/samsonjs/AsyncMonitor)
5+
[![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fsamsonjs%2FAsyncMonitor%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/samsonjs/AsyncMonitor)
6+
7+
## Overview
8+
9+
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.
10+
11+
It uses a Swift `Task` to ensure that all resources are properly cleaned up when the `AsyncMonitor` is cancelled or deallocated.
12+
13+
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.
14+
15+
## Installation
16+
17+
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.
18+
19+
[file a new issue]: https://github.com/samsonjs/AsyncMonitor/issues/new
20+
21+
### Supported Platforms
22+
23+
This package is supported on iOS 18.0+ and macOS 15.0+.
24+
25+
### Xcode
26+
27+
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.
28+
29+
### Swift Package Manager (SPM)
30+
31+
When you're integrating this using SPM on its own then add this to the list of dependencies your Package.swift file:
32+
33+
```swift
34+
.package(url: "https://github.com/samsonjs/AsyncMonitor.git", .upToNextMajor(from: "0.1.0"))
35+
```
36+
37+
and then add `"AsyncMonitor"` to the list of dependencies in your target as well.
38+
39+
## Usage
40+
41+
The simplest example uses a closure that receives the notification:
42+
43+
```swift
44+
import AsyncMonitor
45+
46+
@MainActor class SimplestVersion {
47+
let cancellable = NotificationCenter.default
48+
.notifications(named: .NSCalendarDayChanged).map(\.name)
49+
.monitor { _ in
50+
print("The date is now \(Date.now)")
51+
}
52+
}
53+
```
54+
55+
This example uses the context parameter to avoid reference cycles with `self`:
56+
57+
```swift
58+
import AsyncMonitor
59+
60+
@MainActor class WithContext {
61+
var cancellables = Set<AnyAsyncCancellable>()
62+
63+
init() {
64+
NotificationCenter.default
65+
.notifications(named: .NSCalendarDayChanged).map(\.name)
66+
.monitor(context: self) { _self, _ in
67+
_self.dayChanged()
68+
}.store(in: &cancellables)
69+
}
70+
71+
func dayChanged() {
72+
print("The date is now \(Date.now)")
73+
}
74+
}
75+
```
76+
77+
The closure is async so you can await in there if you need to.
78+
79+
## License
80+
81+
Copyright © 2025 [Sami Samhuri](https://samhuri.net) <[email protected]>. Released under the terms of the [MIT License][MIT].
82+
83+
[MIT]: https://sjs.mit-license.org
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class AnyAsyncCancellable: AsyncCancellable {
2+
let canceller: () -> Void
3+
4+
init<AC: AsyncCancellable>(cancellable: AC) {
5+
canceller = { cancellable.cancel() }
6+
}
7+
8+
deinit {
9+
cancel()
10+
}
11+
12+
// MARK: AsyncCancellable conformance
13+
14+
public func cancel() {
15+
canceller()
16+
}
17+
18+
// MARK: Hashable conformance
19+
20+
public static func == (lhs: AnyAsyncCancellable, rhs: AnyAsyncCancellable) -> Bool {
21+
ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
22+
}
23+
24+
public func hash(into hasher: inout Hasher) {
25+
hasher.combine(ObjectIdentifier(self))
26+
}
27+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public protocol AsyncCancellable: Hashable {
2+
func cancel()
3+
4+
func store(in set: inout Set<AnyAsyncCancellable>)
5+
}
6+
7+
public extension AsyncCancellable {
8+
func store(in set: inout Set<AnyAsyncCancellable>) {
9+
set.insert(AnyAsyncCancellable(cancellable: self))
10+
}
11+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public final class AsyncMonitor: Hashable, AsyncCancellable {
2+
let task: Task<Void, Never>
3+
4+
public init<Element: Sendable>(
5+
isolation: isolated (any Actor)? = #isolation,
6+
sequence: any AsyncSequence<Element, Never>,
7+
performing block: @escaping (Element) async -> Void
8+
) {
9+
self.task = Task {
10+
_ = isolation // use capture trick to inherit isolation
11+
12+
for await element in sequence {
13+
await block(element)
14+
}
15+
}
16+
}
17+
18+
deinit {
19+
cancel()
20+
}
21+
22+
// MARK: AsyncCancellable conformance
23+
24+
public func cancel() {
25+
task.cancel()
26+
}
27+
28+
// MARK: Hashable conformance
29+
30+
public static func == (lhs: AsyncMonitor, rhs: AsyncMonitor) -> Bool {
31+
lhs.task == rhs.task
32+
}
33+
34+
public func hash(into hasher: inout Hasher) {
35+
hasher.combine(task)
36+
}
37+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public extension AsyncSequence where Element: Sendable, Failure == Never {
2+
func monitor(
3+
isolation: isolated (any Actor)? = #isolation,
4+
_ block: @escaping (Element) async -> Void
5+
) -> AsyncMonitor {
6+
AsyncMonitor(isolation: isolation, sequence: self, performing: block)
7+
}
8+
9+
func monitor<Context: AnyObject>(
10+
isolation: isolated (any Actor)? = #isolation,
11+
context: Context,
12+
_ block: @escaping (Context, Element) async -> Void
13+
) -> AsyncMonitor {
14+
AsyncMonitor(isolation: isolation, sequence: self) { [weak context] element in
15+
guard let context else { return }
16+
await block(context, element)
17+
}
18+
}
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public import Foundation
2+
3+
extension KeyPath: @unchecked @retroactive Sendable where Value: Sendable {}
4+
5+
public extension NSObjectProtocol where Self: NSObject {
6+
func values<Value: Sendable>(
7+
for keyPath: KeyPath<Self, Value>,
8+
options: NSKeyValueObservingOptions = [],
9+
changeHandler: @escaping @MainActor (Value) -> Void
10+
) -> any AsyncCancellable {
11+
let (stream, continuation) = AsyncStream<Value>.makeStream()
12+
let token = self.observe(keyPath, options: options) { object, _ in
13+
continuation.yield(object[keyPath: keyPath])
14+
}
15+
return stream.monitor { @MainActor value in
16+
_ = token // keep this alive
17+
changeHandler(value)
18+
}
19+
}
20+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import Foundation
2+
import Testing
3+
@testable import AsyncMonitor
4+
5+
@MainActor class AsyncMonitorTests {
6+
let center = NotificationCenter()
7+
let name = Notification.Name("a random notification")
8+
9+
private var subject: AsyncMonitor?
10+
11+
@Test func callsBlockWhenNotificationsArePosted() async throws {
12+
await withCheckedContinuation { [center, name] continuation in
13+
subject = center.notifications(named: name).map(\.name).monitor { receivedName in
14+
#expect(name == receivedName)
15+
continuation.resume()
16+
}
17+
Task {
18+
center.post(name: name, object: nil)
19+
}
20+
}
21+
}
22+
23+
@Test func doesNotCallBlockWhenOtherNotificationsArePosted() async throws {
24+
subject = center.notifications(named: name).map(\.name).monitor { receivedName in
25+
Issue.record("Called for irrelevant notification \(receivedName)")
26+
}
27+
Task {
28+
center.post(name: Notification.Name("something else"), object: nil)
29+
}
30+
try await Task.sleep(for: .milliseconds(10))
31+
}
32+
33+
@Test func stopsCallingBlockWhenDeallocated() async throws {
34+
subject = center.notifications(named: name).map(\.name).monitor { _ in
35+
Issue.record("Called after deallocation")
36+
}
37+
38+
Task {
39+
subject = nil
40+
center.post(name: name, object: nil)
41+
}
42+
43+
try await Task.sleep(for: .milliseconds(10))
44+
}
45+
46+
class Owner {
47+
let deinitHook: () -> Void
48+
49+
private var cancellable: (any AsyncCancellable)?
50+
51+
@MainActor init(center: NotificationCenter, deinitHook: @escaping () -> Void) {
52+
self.deinitHook = deinitHook
53+
let name = Notification.Name("irrelevant name")
54+
cancellable = center.notifications(named: name).map(\.name)
55+
.monitor(context: self) { _, _ in }
56+
}
57+
58+
deinit {
59+
deinitHook()
60+
}
61+
}
62+
63+
private var owner: Owner?
64+
65+
@Test(.timeLimit(.minutes(1))) func doesNotCreateReferenceCyclesWithContext() async throws {
66+
await withCheckedContinuation { continuation in
67+
self.owner = Owner(center: center) {
68+
continuation.resume()
69+
}
70+
self.owner = nil
71+
}
72+
}
73+
74+
@Test func stopsCallingBlockWhenContextIsDeallocated() async throws {
75+
var context: NSObject? = NSObject()
76+
subject = center.notifications(named: name).map(\.name)
77+
.monitor(context: context!) { context, receivedName in
78+
Issue.record("Called after context was deallocated")
79+
}
80+
context = nil
81+
Task {
82+
center.post(name: name, object: nil)
83+
}
84+
try await Task.sleep(for: .milliseconds(10))
85+
}
86+
}

0 commit comments

Comments
 (0)