@@ -41,6 +41,7 @@ extension Middleware {
41
41
}
42
42
43
43
public struct Middlewares < StateType: State > {
44
+ let id : UInt64
44
45
private( set) var middleware : AnyMiddleware
45
46
}
46
47
@@ -80,12 +81,30 @@ public struct Subscription<StateType: State> {
80
81
}
81
82
}
82
83
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
+ }
83
90
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
+ }
84
102
85
103
// MARK: - Core
86
104
87
105
public class Core < StateType: State > {
88
106
107
+ private var middlewareCounter = Counter ( )
89
108
private let jobQueue : DispatchQueue
90
109
91
110
private let subscriptionsSyncQueue = DispatchQueue ( label: " reactor.core.subscription.sync " )
@@ -103,7 +122,7 @@ public class Core<StateType: State> {
103
122
}
104
123
}
105
124
106
- private let middlewares : [ Middlewares < StateType > ]
125
+ private var middlewares : [ Middlewares < StateType > ]
107
126
public private ( set) var state : StateType {
108
127
didSet {
109
128
subscriptions = subscriptions. filter { $0. subscriber != nil }
@@ -115,7 +134,11 @@ public class Core<StateType: State> {
115
134
116
135
public init ( state: StateType , middlewares: [ AnyMiddleware ] = [ ] ) {
117
136
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
119
142
if #available( macOS 10 . 10 , * ) {
120
143
self . jobQueue = DispatchQueue ( label: " reactor.core.queue " , qos: . userInitiated, attributes: [ ] )
121
144
} else {
@@ -154,5 +177,19 @@ public class Core<StateType: State> {
154
177
command. execute ( state: self . state, core: self )
155
178
}
156
179
}
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
+ self . jobQueue. sync {
188
+ if let index = self . middlewares. firstIndex ( where: { $0. id == wrapper. id } ) {
189
+ self . middlewares. remove ( at: index)
190
+ }
191
+ }
192
+ }
193
+ }
157
194
158
195
}
0 commit comments