Skip to content

Commit

Permalink
Make StoreTransform a Subscriber, remove iOS 14 limit to lensing
Browse files Browse the repository at this point in the history
  • Loading branch information
Qata committed Nov 9, 2020
1 parent 0fee069 commit 738a2dc
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions Sources/RecombinePackage/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ public class Store<State, Action>: ObservableObject {
.store(in: &cancellables)
}

@available(iOS 14, *)
public func lensing<SubState>(_ keyPath: KeyPath<State, SubState>) -> StoreTransform<State, SubState, Action> {
.init(store: self, lensing: keyPath)
}
Expand Down Expand Up @@ -67,16 +66,20 @@ public class StoreTransform<Underlying, State, Action>: ObservableObject {
public private(set) var state: State
private let store: Store<Underlying, Action>
private let keyPath: KeyPath<Underlying, State>
private var cancellables = Set<AnyCancellable>()

@available(iOS 14, *)
public required init(store: Store<Underlying, Action>, lensing keyPath: KeyPath<Underlying, State>) {
self.store = store
self.keyPath = keyPath
state = store.state[keyPath: keyPath]
store.$state.map { $0[keyPath: keyPath] }.assign(to: &$state)
store.$state
.map { $0[keyPath: keyPath] }
.sink { [unowned self] state in
self.state = state
}
.store(in: &cancellables)
}

@available(iOS 14, *)
public func lensing<SubState>(_ keyPath: KeyPath<State, SubState>) -> StoreTransform<Underlying, SubState, Action> {
.init(store: store, lensing: self.keyPath.appending(path: keyPath))
}
Expand All @@ -89,3 +92,17 @@ public class StoreTransform<Underlying, State, Action>: ObservableObject {
store.dispatch(actions)
}
}

extension StoreTransform: Subscriber {
public func receive(subscription: Subscription) {
subscription.store(in: &cancellables)
subscription.request(.unlimited)
}

public func receive(_ input: Action) -> Subscribers.Demand {
store.dispatch(input)
return .unlimited
}

public func receive(completion: Subscribers.Completion<Never>) {}
}

0 comments on commit 738a2dc

Please sign in to comment.