Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addressing State being consistent in value from the first check (#90) #91

Merged
merged 2 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion Sources/AppState/Application/Types/State/Application+State.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,31 @@ extension Application {
scope.key,
as: State<Value>.self
)
else { return _value }
else {
defer {
let setValue = {
shared.cache.set(
value: Application.State(
type: .state,
initial: _value,
scope: scope
),
forKey: scope.key
)
}

#if !os(Linux) && !os(Windows)
Task {
await MainActor.run {
setValue()
}
}
#else
setValue()
#endif
}
return _value
}
return state._value
}
set {
Expand Down
23 changes: 22 additions & 1 deletion Tests/AppStateTests/AppStateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ fileprivate extension Application {
var username: State<String> {
state(initial: "Leif")
}


var date: State<Date> {
state(initial: Date())
}

var colors: State<[String: String]> {
state(initial: ["primary": "#A020F0"])
}
Expand Down Expand Up @@ -69,6 +73,23 @@ final class AppStateTests: XCTestCase {
XCTAssertEqual(appState.value, "0xL")
XCTAssertEqual(Application.state(\.username).value, "0xL")
}

func testStateClosureCachesValueOnGet() async {
let dateState: Application.State = Application.state(\.date)
#if !os(Linux) && !os(Windows)
await MainActor.run {
let copyOfDateState: Application.State =
Application.state(\.date)

XCTAssertEqual(copyOfDateState.value, dateState.value)
}
#else
let copyOfDateState: Application.State =
Application.state(\.date)

XCTAssertEqual(copyOfDateState.value, dateState.value)
#endif
}

func testPropertyWrappers() {
let exampleView = ExampleView()
Expand Down
Loading