I am using DispatchSourceFileSystemObject
to listen to file changes; I created a small function that takes a URL
and listen to the event changed in the file.
private struct MonitoredFile {
let url: URL
let fileHandle: FileHandle
let source: DispatchSourceFileSystemObject
init(url: URL) throws {
self.url = url
fileHandle = try FileHandle(forReadingFrom: url)
source = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fileHandle.fileDescriptor,
eventMask: .all,
queue: DispatchQueue.main
)
}
}
public func startMonitoring(url: URL) -> AsyncThrowingStream<DispatchSource.FileSystemEvent, Error> {
AsyncThrowingStream { continuation in
do {
let monitoredFile = try MonitoredFile(url: url)
monitoredFile.source.setEventHandler {
continuation.yield(monitoredFile.source.data)
}
monitoredFile.source.setCancelHandler {
do {
try monitoredFile.fileHandle.close()
} catch {
continuation.finish(throwing: FileMonitorError.closingFileHandleError(url))
}
}
try monitoredFile.fileHandle.seekToEnd()
monitoredFile.source.resume()
} catch {
continuation.finish(throwing: FileMonitorError.failedMonitoringFile(url))
}
}
}
Later, I noticed that Listening to multiple files in the same directory would be better than just one.
I saw that swift-async-algorithms
has a merge
function that merges two or three AsyncStream
.
My question is, how can I merge multiple streams and not limit them to a specific number?