Skip to content

Commit

Permalink
Merge pull request #2 from mattmassicotte/feature/asyncstream
Browse files Browse the repository at this point in the history
FSEventAsyncStream
  • Loading branch information
Frizlab authored Jul 18, 2023
2 parents bf33986 + 739da7d commit 70bbea4
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Readme.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ Use SPM.
== How to Use?
[code,swift]
----
/* Using a standard callback. */
let w = FSEventStream(path: "awesome/path", callback: { stream, event in NSLog("%@", String(describing: event)) })
w?.startWatching()
/* Or with an AsyncStream. */
Task {
for await event in FSEventAsyncStream(path: "awesome/path") {
print(event)
}
}
----
55 changes: 55 additions & 0 deletions Sources/FSEventsWrapper/FSEventAsyncStream.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import Foundation



/* Needed to guard the availability of `AsyncStream.makeStream`.
* Once Xcode 15 is released, it should be safe to remove this. */
#if compiler(>=5.9)

/** An AsyncSequence of `FSEvent` objects. */
@available(macOS 10.15, *)
public struct FSEventAsyncStream : AsyncSequence {

public typealias Element = FSEvent

public struct FSEventAsyncIterator : AsyncIteratorProtocol {

private let eventStream: FSEventStream?
private var streamIterator: AsyncStream<FSEvent>.Iterator

init(path: String, flags: FSEventStreamCreateFlags) {
let (stream, continuation) = AsyncStream<FSEvent>.makeStream()

self.eventStream = FSEventStream(path: path, fsEventStreamFlags: flags, callback: { _, event in
continuation.yield(event)
})

self.streamIterator = stream.makeAsyncIterator()
self.eventStream?.startWatching()

if eventStream == nil {
continuation.finish()
}
}

public mutating func next() async -> FSEvent? {
await streamIterator.next()
}

}

public let path: String
public let flags: FSEventStreamCreateFlags

public init(path: String, flags: FSEventStreamCreateFlags = FSEventStreamCreateFlags(kFSEventStreamCreateFlagNone)) {
self.path = path
self.flags = flags
}

public func makeAsyncIterator() -> FSEventAsyncIterator {
FSEventAsyncIterator(path: path, flags: flags)
}

}

#endif

0 comments on commit 70bbea4

Please sign in to comment.