-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLensedStore.swift
91 lines (79 loc) · 2.62 KB
/
LensedStore.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Combine
import SwiftUI
public struct StoreLens<State: Equatable, AsyncAction, SyncAction>: StoreProtocol {
public var combineIdentifier: CombineIdentifier = .init()
public typealias Action = EitherAction<AsyncAction, SyncAction>
public typealias Dispatch = (Bool, Bool, [Action]) -> Void
private let _dispatch: Dispatch
private var cancellable: AnyCancellable?
public var stateSubject: CurrentValueSubject<State, Never>
public var state: State {
stateSubject.value
}
public var statePublisher: AnyPublisher<State, Never> {
stateSubject.eraseToAnyPublisher()
}
public init<StatePublisher: Publisher>(
initial: State,
statePublisher: StatePublisher,
dispatch: @escaping Dispatch
)
where StatePublisher.Output == State, StatePublisher.Failure == Never
{
_dispatch = dispatch
stateSubject = .init(initial)
cancellable = statePublisher
.removeDuplicates()
.sink(receiveValue: stateSubject.send)
}
public func dispatch<S>(
serially: Bool,
collect: Bool,
actions: S
)
where S: Sequence, S.Element == Action
{
_dispatch(serially, collect, .init(actions))
}
}
public class LensedStore<State: Equatable, AsyncAction, SyncAction>: StoreProtocol, ObservableObject {
public typealias Action = EitherAction<AsyncAction, SyncAction>
public typealias Underlying = StoreLens<State, AsyncAction, SyncAction>
private let underlying: Underlying
private var cancellable: AnyCancellable?
@Published public var state: State
public var statePublisher: AnyPublisher<State, Never> {
$state.eraseToAnyPublisher()
}
public init(from storeLens: Underlying) {
underlying = storeLens
state = storeLens.stateSubject.value
cancellable = storeLens.stateSubject
.dropFirst()
.assign(to: \.state, on: self)
}
public convenience init<StatePublisher: Publisher>(
initial: State,
statePublisher: StatePublisher,
dispatch: @escaping Underlying.Dispatch
)
where StatePublisher.Output == State, StatePublisher.Failure == Never
{
self.init(
from: .init(
initial: initial,
statePublisher: statePublisher,
dispatch: dispatch
)
)
}
public func dispatch<S>(
serially: Bool,
collect: Bool,
actions: S
)
where S: Sequence, S.Element == Action
{
underlying.dispatch(serially: serially, collect: collect, actions: actions)
}
}