forked from ReactiveCocoa/ReactiveCocoa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProperty.swift
262 lines (214 loc) · 7.72 KB
/
Property.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import Foundation
import enum Result.NoError
/// Represents a property that allows observation of its changes.
public protocol PropertyType {
associatedtype Value
/// The current value of the property.
var value: Value { get }
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time.
var producer: SignalProducer<Value, NoError> { get }
/// A signal that will send the property's changes over time.
var signal: Signal<Value, NoError> { get }
}
/// A read-only property that allows observation of its changes.
public struct AnyProperty<Value>: PropertyType {
private let _value: () -> Value
private let _producer: () -> SignalProducer<Value, NoError>
private let _signal: () -> Signal<Value, NoError>
public var value: Value {
return _value()
}
public var producer: SignalProducer<Value, NoError> {
return _producer()
}
public var signal: Signal<Value, NoError> {
return _signal()
}
/// Initializes a property as a read-only view of the given property.
public init<P: PropertyType where P.Value == Value>(_ property: P) {
_value = { property.value }
_producer = { property.producer }
_signal = { property.signal }
}
/// Initializes a property that first takes on `initialValue`, then each value
/// sent on a signal created by `producer`.
public init(initialValue: Value, producer: SignalProducer<Value, NoError>) {
let mutableProperty = MutableProperty(initialValue)
mutableProperty <~ producer
self.init(mutableProperty)
}
/// Initializes a property that first takes on `initialValue`, then each value
/// sent on `signal`.
public init(initialValue: Value, signal: Signal<Value, NoError>) {
let mutableProperty = MutableProperty(initialValue)
mutableProperty <~ signal
self.init(mutableProperty)
}
}
extension PropertyType {
/// Maps the current value and all subsequent values to a new value.
public func map<U>(transform: Value -> U) -> AnyProperty<U> {
let mappedProducer = SignalProducer<U, NoError> { observer, disposable in
disposable += ActionDisposable { self }
disposable += self.producer.map(transform).start(observer)
}
return AnyProperty(initialValue: transform(value), producer: mappedProducer)
}
}
/// A property that never changes.
public struct ConstantProperty<Value>: PropertyType {
public let value: Value
public let producer: SignalProducer<Value, NoError>
public let signal: Signal<Value, NoError>
/// Initializes the property to have the given value.
public init(_ value: Value) {
self.value = value
self.producer = SignalProducer(value: value)
self.signal = .empty
}
}
/// Represents an observable property that can be mutated directly.
///
/// Only classes can conform to this protocol, because instances must support
/// weak references (and value types currently do not).
public protocol MutablePropertyType: class, PropertyType {
var value: Value { get set }
}
/// A mutable property of type `Value` that allows observation of its changes.
///
/// Instances of this class are thread-safe.
public final class MutableProperty<Value>: MutablePropertyType {
private let observer: Signal<Value, NoError>.Observer
/// Need a recursive lock around `value` to allow recursive access to
/// `value`. Note that recursive sets will still deadlock because the
/// underlying producer prevents sending recursive events.
private let lock: NSRecursiveLock
/// The getter of the underlying storage, which may outlive the property
/// if a returned producer is being retained.
private let getter: () -> Value
/// The setter of the underlying storage.
private let setter: Value -> Void
/// The current value of the property.
///
/// Setting this to a new value will notify all observers of any Signals
/// created from the `values` producer.
public var value: Value {
get {
return withValue { $0 }
}
set {
swap(newValue)
}
}
/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, NoError>
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public var producer: SignalProducer<Value, NoError> {
return SignalProducer { [getter, weak self] producerObserver, producerDisposable in
if let strongSelf = self {
strongSelf.withValue { value in
producerObserver.sendNext(value)
producerDisposable += strongSelf.signal.observe(producerObserver)
}
} else {
/// As the setter would have been deinitialized with the property,
/// the underlying storage would be immutable, and locking is no longer necessary.
producerObserver.sendNext(getter())
producerObserver.sendCompleted()
}
}
}
/// Initializes the property with the given value to start.
public init(_ initialValue: Value) {
var value = initialValue
lock = NSRecursiveLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.MutableProperty"
getter = { value }
setter = { newValue in value = newValue }
(signal, observer) = Signal.pipe()
}
/// Atomically replaces the contents of the variable.
///
/// Returns the old value.
public func swap(newValue: Value) -> Value {
return modify { _ in newValue }
}
/// Atomically modifies the variable.
///
/// Returns the old value.
public func modify(@noescape action: (Value) throws -> Value) rethrows -> Value {
return try withValue { value in
let newValue = try action(value)
setter(newValue)
observer.sendNext(newValue)
return value
}
}
/// Atomically performs an arbitrary action using the current value of the
/// variable.
///
/// Returns the result of the action.
public func withValue<Result>(@noescape action: (Value) throws -> Result) rethrows -> Result {
lock.lock()
defer { lock.unlock() }
return try action(getter())
}
deinit {
observer.sendCompleted()
}
}
infix operator <~ {
associativity right
// Binds tighter than assignment but looser than everything else
precedence 93
}
/// Binds a signal to a property, updating the property's value to the latest
/// value sent by the signal.
///
/// The binding will automatically terminate when the property is deinitialized,
/// or when the signal sends a `Completed` event.
public func <~ <P: MutablePropertyType>(property: P, signal: Signal<P.Value, NoError>) -> Disposable {
let disposable = CompositeDisposable()
disposable += property.producer.startWithCompleted {
disposable.dispose()
}
disposable += signal.observe { [weak property] event in
switch event {
case let .Next(value):
property?.value = value
case .Completed:
disposable.dispose()
case .Failed, .Interrupted:
break
}
}
return disposable
}
/// Creates a signal from the given producer, which will be immediately bound to
/// the given property, updating the property's value to the latest value sent
/// by the signal.
///
/// The binding will automatically terminate when the property is deinitialized,
/// or when the created signal sends a `Completed` event.
public func <~ <P: MutablePropertyType>(property: P, producer: SignalProducer<P.Value, NoError>) -> Disposable {
var disposable: Disposable!
producer.startWithSignal { signal, signalDisposable in
property <~ signal
disposable = signalDisposable
property.producer.startWithCompleted {
signalDisposable.dispose()
}
}
return disposable
}
/// Binds `destinationProperty` to the latest values of `sourceProperty`.
///
/// The binding will automatically terminate when either property is
/// deinitialized.
public func <~ <Destination: MutablePropertyType, Source: PropertyType where Source.Value == Destination.Value>(destinationProperty: Destination, sourceProperty: Source) -> Disposable {
return destinationProperty <~ sourceProperty.producer
}