Skip to content

Simplify/fix #1784 #1785

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

Merged
merged 3 commits into from
Jan 3, 2023
Merged
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
42 changes: 13 additions & 29 deletions Sources/ComposableArchitecture/ViewStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -466,11 +466,14 @@ public final class ViewStore<ViewState, ViewAction>: ObservableObject {
get: @escaping (ViewState) -> Value,
send valueToAction: @escaping (Value) -> ViewAction
) -> Binding<Value> {
@ObservedState var val = get(self.state)
return .init(
get: { [$val] in $val.wrappedValue },
set: { [weak self] in self?.send(valueToAction($0)) }
ObservedObject(
wrappedValue: ObservedState(
initialValue: get(self.state),
send: { self.send(valueToAction($0)) }
)
)
.projectedValue
.wrappedValue
}

/// Derives a binding from the store that prevents direct writes to state and instead sends
Expand Down Expand Up @@ -745,31 +748,12 @@ public struct StorePublisher<State>: Publisher {
}
}

final private class ValueWrapper<V>: ObservableObject {
var value: V {
willSet { objectWillChange.send() }
}

init(_ value: V) {
self.value = value
}
}

@propertyWrapper private struct ObservedState<Value>: DynamicProperty {
@ObservedObject private var box: ValueWrapper<Value>

var wrappedValue: Value {
get { box.value }
nonmutating set { box.value = newValue }
}
private final class ObservedState<Value>: ObservableObject {
@Published var wrappedValue: Value
var cancellable: AnyCancellable?

var projectedValue: Binding<Value> {
.init(
get: { wrappedValue },
set: { wrappedValue = $0 }
)
}
init(wrappedValue value: Value) {
self._box = ObservedObject(wrappedValue: .init(value))
init(initialValue: Value, send: @escaping (Value) -> Void) {
self.wrappedValue = initialValue
self.cancellable = self.$wrappedValue.dropFirst().sink(receiveValue: send)
}
}