History
Loading...
Loading...
September 16, 2025
.onReceive() with Timer.publish() to create self-managing periodic updates that automatically respect view lifecycle. The subscription automatically cancels when the view disappears, preventing memory leaks without manual cleanup.This pattern uses `onReceive()` to handle publisher subscriptions that automatically respect SwiftUI's view lifecycle. The timer subscription is created when the view appears and automatically cancelled when destroyed, while the filter allows for conditional processing.
struct ContentView: View {
@State private var currentTime = Date()
@State private var isActive = true
var body: some View {
VStack {
Text(currentTime.formatted(date: .omitted, time: .standard))
.font(.largeTitle.monospacedDigit())
Button(isActive ? "Pause" : "Resume") {
isActive.toggle()
}
}
.onReceive(
Timer.publish(every: 1, on: .main, in: .common)
.autoconnect()
.filter { _ in isActive }
) { time in
currentTime = time
}
.onDisappear {
isActive = false
}
}
}SwiftUI's `onReceive()` provides automatic subscription management tied to view lifecycle, eliminating manual cleanup code. Using filters with publishers keeps the subscription alive while controlling when events are processed, leading to more efficient and leak-free reactive code patterns.