Skip to content

Commit de8d76f

Browse files
committed
Adds support for registering middleware after construction and removing that middleware
1 parent 66c6c85 commit de8d76f

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

Sources/Reactor.swift

+37-2
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ extension Middleware {
4141
}
4242

4343
public struct Middlewares<StateType: State> {
44+
let id: UInt64
4445
private(set) var middleware: AnyMiddleware
4546
}
4647

@@ -80,12 +81,30 @@ public struct Subscription<StateType: State> {
8081
}
8182
}
8283

84+
extension String {
85+
static func random(length: Int = 20) -> String {
86+
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
87+
return String((0..<length).map{ _ in base.randomElement()! })
88+
}
89+
}
8390

91+
class Counter {
92+
private var queue = DispatchQueue(label: String.random())
93+
private (set) var value: UInt64 = 0
94+
95+
func increment() -> UInt64 {
96+
queue.sync {
97+
value += 1
98+
return value
99+
}
100+
}
101+
}
84102

85103
// MARK: - Core
86104

87105
public class Core<StateType: State> {
88106

107+
private var middlewareCounter = Counter()
89108
private let jobQueue:DispatchQueue
90109

91110
private let subscriptionsSyncQueue = DispatchQueue(label: "reactor.core.subscription.sync")
@@ -103,7 +122,7 @@ public class Core<StateType: State> {
103122
}
104123
}
105124

106-
private let middlewares: [Middlewares<StateType>]
125+
private var middlewares: [Middlewares<StateType>]
107126
public private (set) var state: StateType {
108127
didSet {
109128
subscriptions = subscriptions.filter { $0.subscriber != nil }
@@ -115,7 +134,11 @@ public class Core<StateType: State> {
115134

116135
public init(state: StateType, middlewares: [AnyMiddleware] = []) {
117136
self.state = state
118-
self.middlewares = middlewares.map(Middlewares.init)
137+
var tempMiddlewares = [Middlewares<StateType>]()
138+
for m in middlewares {
139+
tempMiddlewares.append(Middlewares(id: middlewareCounter.increment(), middleware: m))
140+
}
141+
self.middlewares = tempMiddlewares
119142
if #available(macOS 10.10, *) {
120143
self.jobQueue = DispatchQueue(label: "reactor.core.queue", qos: .userInitiated, attributes: [])
121144
} else {
@@ -154,5 +177,17 @@ public class Core<StateType: State> {
154177
command.execute(state: self.state, core: self)
155178
}
156179
}
180+
181+
public func observe(with middleware: AnyMiddleware) -> () -> () {
182+
let wrapper = Middlewares<StateType>(id: middlewareCounter.increment(), middleware: middleware)
183+
jobQueue.async {
184+
self.middlewares.append(wrapper)
185+
}
186+
return {
187+
if let index = self.middlewares.firstIndex(where: { $0.id == wrapper.id }) {
188+
self.middlewares.remove(at: index)
189+
}
190+
}
191+
}
157192

158193
}

0 commit comments

Comments
 (0)