Skip to content

Commit

Permalink
Leif/small improvements (#73)
Browse files Browse the repository at this point in the history
* Revert "Remove State wrapping of stored and sync values (#70)"

This reverts commit 2f8d00f.

* Remove synchronize calls

The only recommended time to call this method is
upon app launch, or upon returning to the
foreground, to ensure that the in-memory key-value
store representation is up-to-date.

* Move files to new folders
  • Loading branch information
0xLeif authored Jan 18, 2024
1 parent 9ac0ed4 commit e74c84c
Show file tree
Hide file tree
Showing 19 changed files with 18 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ extension Application {

For example, it could be used to scope a state to a particular screen or user interaction flow.
*/
struct Scope {
public struct Scope {
/// The name of the scope context
let name: String
public let name: String

/// The specific id for this scope context
let id: String
public let id: String

/// Key computed property which builds a unique key for a given scope by combining `name` and `id` separated by "/"
var key: String {
public var key: String {
"\(name)/\(id)"
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ extension Application {
get {
let cachedValue = shared.cache.get(
scope.key,
as: Value.self
as: State<Value>.self
)

if let cachedValue = cachedValue {
return cachedValue
return cachedValue.value
}

guard
Expand All @@ -41,7 +41,11 @@ extension Application {
userDefaults.removeObject(forKey: scope.key)
} else {
shared.cache.set(
value: newValue,
value: Application.State(
type: .stored,
initial: newValue,
scope: scope
),
forKey: scope.key
)
userDefaults.set(newValue, forKey: scope.key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ extension Application {
guard
let cachedValue = shared.cache.get(
scope.key,
as: Value.self
as: State<Value>.self
)
else { return initial() }

return cachedValue
return cachedValue.value
}
set {
let mirror = Mirror(reflecting: newValue)
Expand All @@ -67,17 +67,19 @@ extension Application {
mirror.children.isEmpty {
shared.cache.remove(scope.key)
icloudStore.removeObject(forKey: scope.key)
icloudStore.synchronize()
} else {
shared.cache.set(
value: newValue,
value: Application.State(
type: .sync,
initial: newValue,
scope: scope
),
forKey: scope.key
)

do {
let data = try JSONEncoder().encode(newValue)
icloudStore.set(data, forKey: scope.key)
icloudStore.synchronize()
} catch {
Application.log(
error: error,
Expand Down

0 comments on commit e74c84c

Please sign in to comment.