Created
April 3, 2021 16:10
-
-
Save koher/ecf5471a8f47c55f70b575350936b57d to your computer and use it in GitHub Desktop.
An example how to use onReceive with @published
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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