Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lightandshadow68/26cee6dfd98ed96313231a0f04466b0d to your computer and use it in GitHub Desktop.
Save lightandshadow68/26cee6dfd98ed96313231a0f04466b0d to your computer and use it in GitHub Desktop.
Remote @State
import SwiftUI
@main
struct TestProjectApp: App {
var appState = AppState()
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
RootView(appState: appState)
}
.onChange(of: scenePhase) { oldValue, newValue in
if newValue == .active {
appState.show = true
}
}
}
}
struct RootView: View {
var appState: AppState
var body: some View {
VStack {
SpecialView()
if appState.show {
Text("Some cool text")
}
}
}
}
struct SpecialView: View {
var viewModel = ViewModel()
var body: some View {
Text("\(viewModel.count)")
Button ("Update Message") {
viewModel.increment()
}
}
}
@Observable class AppState {
var show: Bool = false
init() {
print("✅ AppState was inited")
}
deinit {
print("❌ AppState was deinited")
}
}
@Observable class ViewModel {
var count = 0
init() {
print("✅ View model was inited")
}
func increment() {
count += 1
}
deinit {
print("❌ View model was deinited")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment