Last active
May 20, 2024 02:56
-
-
Save lightandshadow68/26cee6dfd98ed96313231a0f04466b0d to your computer and use it in GitHub Desktop.
Remote @State
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 | |
@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