Skip to content

Commit

Permalink
Addressing State being consistent in value from the first check (#90)
Browse files Browse the repository at this point in the history
* Update README.md

- change variable appState name to usernameState to reflect the value of the variable.

* Update README.md

- update appState variable name to usernameState for the whole read and write section

* Made changes to State to cache value when it is first retrieved.
Added a test to ensure that state value is consistent from when it is first checked

* Made additions to testStateClosureCachesValueOnGet to account for async
  • Loading branch information
rmh211 authored Jan 26, 2024
1 parent e03dc89 commit 9354304
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
30 changes: 29 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,36 @@ extension Application {
scope.key,
as: State<Value>.self
)
else { return _value }
else {
defer {
#if !os(Linux) && !os(Windows)
Task {
await MainActor.run {
shared.cache.set(
value: Application.State(
type: .state,
initial: _value,
scope: scope
),
forKey: scope.key
)
}
}

#else
shared.cache.set(
value: Application.State(
type: .state,
initial: _value,
scope: scope
),
forKey: scope.key
)

#endif
}
return _value
}
return state._value
}
set {
Expand Down
21 changes: 20 additions & 1 deletion Tests/AppStateTests/AppStateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ 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 +71,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

0 comments on commit 9354304

Please sign in to comment.