Skip to content

Commit ff8c046

Browse files
committed
Pull publishing state change into subscription
1 parent 0da58df commit ff8c046

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

Sources/Reactor.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,16 @@ public struct Subscription<StateType: State> {
6868
private(set) weak var subscriber: AnySubscriber? = nil
6969
let selector: ((StateType) -> Any)?
7070
let notifyQueue: DispatchQueue
71+
72+
fileprivate func notify(with state: StateType) {
73+
notifyQueue.async {
74+
if let selector = self.selector {
75+
self.subscriber?._update(with: selector(state))
76+
} else {
77+
self.subscriber?._update(with: state)
78+
}
79+
}
80+
}
7181
}
7282

7383

@@ -97,8 +107,8 @@ public class Core<StateType: State> {
97107
public private (set) var state: StateType {
98108
didSet {
99109
subscriptions = subscriptions.filter { $0.subscriber != nil }
100-
for subscription in self.subscriptions {
101-
self.publishStateChange(subscriber: subscription.subscriber, selector: subscription.selector, notifyQueue: subscription.notifyQueue)
110+
for subscription in subscriptions {
111+
subscription.notify(with: state)
102112
}
103113
}
104114
}
@@ -114,26 +124,16 @@ public class Core<StateType: State> {
114124
public func add(subscriber: AnySubscriber, notifyOnQueue queue: DispatchQueue? = DispatchQueue.main, selector: ((StateType) -> Any)? = nil) {
115125
jobQueue.async {
116126
guard !self.subscriptions.contains(where: {$0.subscriber === subscriber}) else { return }
117-
self.subscriptions.append(Subscription(subscriber: subscriber, selector: selector, notifyQueue: queue ?? self.jobQueue))
118-
self.publishStateChange(subscriber: subscriber, selector: selector, notifyQueue: queue ?? self.jobQueue)
127+
let subscription = Subscription(subscriber: subscriber, selector: selector, notifyQueue: queue ?? self.jobQueue)
128+
self.subscriptions.append(subscription)
129+
subscription.notify(with: self.state)
119130
}
120131
}
121132

122133
public func remove(subscriber: AnySubscriber) {
123134
subscriptions = subscriptions.filter { $0.subscriber !== subscriber }
124135
}
125136

126-
private func publishStateChange(subscriber: AnySubscriber?, selector: ((StateType) -> Any)?, notifyQueue: DispatchQueue) {
127-
let state = self.state
128-
notifyQueue.async {
129-
if let selector = selector {
130-
subscriber?._update(with: selector(state))
131-
} else {
132-
subscriber?._update(with: state)
133-
}
134-
}
135-
}
136-
137137
// MARK: - Events
138138

139139
public func fire(event: Event) {

0 commit comments

Comments
 (0)