AsyncMonitor/Tests/AsyncMonitorTests/ReadmeExamples.swift
Sami Samhuri d2b4e0e382
Change the KVO monitoring API
Instead of having a values method that observes and monitors, break out
a values method that returns an AsyncStream and then a monitorValues
method that calls values(for: keyPath).monitor. That method is kind of
superfluous, not sure if it's good to keep it or not.
2025-04-26 17:47:12 -07:00

61 lines
1.4 KiB
Swift

import Foundation
@testable import AsyncMonitor
// MARK: Basics
class SimplestVersion {
let cancellable = NotificationCenter.default
.notifications(named: .NSCalendarDayChanged)
.map(\.name)
.monitor { _ in
print("The date is now \(Date.now)")
}
}
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)")
}
}
// MARK: - Combine
import Combine
class CombineExample {
var cancellables = Set<AnyAsyncCancellable>()
init() {
Timer.publish(every: 1.0, on: .main, in: .common)
.autoconnect()
.values
.monitor { date in
print("Timer fired at \(date)")
}
.store(in: &cancellables)
}
}
// MARK: - KVO
class KVOExample {
var cancellables = Set<AnyAsyncCancellable>()
init() {
let progress = Progress(totalUnitCount: 42)
progress.monitorValues(for: \.fractionCompleted) { fraction in
print("Progress is \(fraction.formatted(.percent))%")
}.store(in: &cancellables)
}
}