Skip to content

Instantly share code, notes, and snippets.

@koher
Created April 3, 2021 16:10
Show Gist options
  • Save koher/ecf5471a8f47c55f70b575350936b57d to your computer and use it in GitHub Desktop.
Save koher/ecf5471a8f47c55f70b575350936b57d to your computer and use it in GitHub Desktop.
An example how to use onReceive with @published
import SwiftUI
struct ContentView: View {
@StateObject private var state: ContentViewState = .init()
var body: some View {
VStack {
Text(state.count.description)
Button("Count Up") { state.countUp() }
Button("Reset") { state.reset() }
}
.onReceive(state.$count) { count in
print(count)
}
}
}
final class ContentViewState: ObservableObject {
@Published private(set) var count: Int = 0
func countUp() {
count += 1
}
func reset() {
count = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment