forked from ReactiveCocoa/ReactiveSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSignal.swift
2410 lines (2151 loc) · 78.1 KB
/
Signal.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur
/// (`Error`). If no failures should be possible, NoError can be specified for
/// `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// A Signal is kept alive until either of the following happens:
/// 1. its input observer receives a terminating event; or
/// 2. it has no active observers, and is not being retained.
public final class Signal<Value, Error: Swift.Error> {
public typealias Observer = ReactiveSwift.Observer<Value, Error>
/// The disposable returned by the signal generator. It would be disposed of
/// when the signal terminates.
private var generatorDisposable: Disposable?
/// The state of the signal.
///
/// `state` synchronizes using Read-Copy-Update. Reads on the event delivery
/// routine are thus wait-free. But modifications, e.g. inserting observers,
/// still have to be serialized, and are required not to mutate in place.
///
/// This suits `Signal` as reads to `status` happens on the critical path of
/// event delivery, while observers bag manipulation or termination generally
/// has a constant occurrence.
///
/// As `SignalState` is a packed object reference (a tagged pointer) that is
/// naturally aligned, reads to are guaranteed to be atomic on all supported
/// hardware architectures of Swift (ARM and x86).
private var state: SignalState<Value, Error>
/// Used to ensure that state updates are serialized.
private let updateLock: NSLock
/// Used to ensure that events are serialized during delivery to observers.
private let sendLock: NSLock
/// Initialize a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// - note: The disposable returned from the closure will be automatically
/// disposed if a terminating event is sent to the observer. The
/// Signal itself will remain alive until the observer is released.
///
/// - parameters:
/// - generator: A closure that accepts an implicitly created observer
/// that will act as an event emitter for the signal.
public init(_ generator: (Observer) -> Disposable?) {
state = .alive(AliveState())
updateLock = NSLock()
updateLock.name = "org.reactivecocoa.ReactiveSwift.Signal.updateLock"
sendLock = NSLock()
sendLock.name = "org.reactivecocoa.ReactiveSwift.Signal.sendLock"
let observer = Observer { [weak self] event in
guard let signal = self else {
return
}
// Thread Safety Notes on `Signal.state`.
//
// - Check if the signal is at a specific state.
//
// Read directly.
//
// - Deliver `value` events with the alive state.
//
// `sendLock` must be acquired.
//
// - Replace the alive state with another.
// (e.g. observers bag manipulation)
//
// `updateLock` must be acquired.
//
// - Transition from `alive` to `terminating` as a result of receiving
// a termination event.
//
// `updateLock` must be acquired, and should fail gracefully if the
// signal has terminated.
//
// - Check if the signal is terminating. If it is, invoke `tryTerminate`
// which transitions the state from `terminating` to `terminated`, and
// delivers the termination event.
//
// Both `sendLock` and `updateLock` must be acquired. The check can be
// relaxed, but the state must be checked again after the locks are
// acquired. Fail gracefully if the state has changed since the relaxed
// read, i.e. a concurrent sender has already handled the termination
// event.
//
// Exploiting the relaxation of reads, please note that false positives
// are intentionally allowed in the `terminating` checks below. As a
// result, normal event deliveries need not acquire `updateLock`.
// Nevertheless, this should not cause the termination event being
// sent multiple times, since `tryTerminate` would not respond to false
// positives.
/// Try to terminate the signal.
///
/// If the signal is alive or has terminated, it fails gracefully. In
/// other words, calling this method as a result of a false positive
/// `terminating` check is permitted.
///
/// - note: The `updateLock` would be acquired.
///
/// - returns: `true` if the attempt succeeds. `false` otherwise.
@inline(__always)
func tryTerminate() -> Bool {
// Acquire `updateLock`. If the termination has still not yet been
// handled, take it over and bump the status to `terminated`.
signal.updateLock.lock()
if case let .terminating(state) = signal.state {
signal.state = .terminated
signal.updateLock.unlock()
for observer in state.observers {
observer.action(state.event)
}
return true
}
signal.updateLock.unlock()
return false
}
if event.isTerminating {
// Recursive events are disallowed for `value` events, but are permitted
// for termination events. Specifically:
//
// - `interrupted`
// It can inadvertently be sent by downstream consumers as part of the
// `SignalProducer` mechanics.
//
// - `completed`
// If a downstream consumer weakly references an object, invocation of
// such consumer may cause a race condition with its weak retain against
// the last strong release of the object. If the `Lifetime` of the
// object is being referenced by an upstream `take(during:)`, a
// signal recursion might occur.
//
// So we would treat termination events specially. If it happens to
// occur while the `sendLock` is acquired, the observer call-out and
// the disposal would be delegated to the current sender, or
// occasionally one of the senders waiting on `sendLock`.
signal.updateLock.lock()
if case let .alive(state) = signal.state {
let newSnapshot = TerminatingState(observers: state.observers,
event: event)
signal.state = .terminating(newSnapshot)
signal.updateLock.unlock()
if signal.sendLock.try() {
// Check whether the terminating state has been handled by a
// concurrent sender. If not, handle it.
let shouldDispose = tryTerminate()
signal.sendLock.unlock()
if shouldDispose {
signal.swapDisposable()?.dispose()
}
}
} else {
signal.updateLock.unlock()
}
} else {
var shouldDispose = false
// The `terminating` status check is performed twice for two different
// purposes:
//
// 1. Within the main protected section
// It guarantees that a recursive termination event sent by a
// downstream consumer, is immediately processed and need not compete
// with concurrent pending senders (if any).
//
// Termination events sent concurrently may also be caught here, but
// not necessarily all of them due to data races.
//
// 2. After the main protected section
// It ensures the termination event sent concurrently that are not
// caught by (1) due to data races would still be processed.
//
// The related PR on the race conditions:
// https://github.com/ReactiveCocoa/ReactiveSwift/pull/112
signal.sendLock.lock()
// Start of the main protected section.
if case let .alive(state) = signal.state {
for observer in state.observers {
observer.action(event)
}
// Check if the status has been bumped to `terminating` due to a
// concurrent or a recursive termination event.
if case .terminating = signal.state {
shouldDispose = tryTerminate()
}
}
// End of the main protected section.
signal.sendLock.unlock()
// Check if the status has been bumped to `terminating` due to a
// concurrent termination event that has not been caught in the main
// protected section.
if !shouldDispose, case .terminating = signal.state {
signal.sendLock.lock()
shouldDispose = tryTerminate()
signal.sendLock.unlock()
}
if shouldDispose {
// Dispose only after notifying observers, so disposal
// logic is consistently the last thing to run.
signal.swapDisposable()?.dispose()
}
}
}
generatorDisposable = generator(observer)
}
/// Swap the generator disposable with `nil`.
///
/// - returns:
/// The generator disposable, or `nil` if it has been disposed of.
private func swapDisposable() -> Disposable? {
if let d = generatorDisposable {
generatorDisposable = nil
return d
}
return nil
}
deinit {
// A signal can deinitialize only when it is not retained and has no
// active observers. So `state` need not be swapped.
swapDisposable()?.dispose()
}
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { _ in nil }
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer in
observer.sendCompleted()
return nil
}
}
/// Create a `Signal` that will be controlled by sending events to an
/// input observer.
///
/// - note: The `Signal` will remain alive until a terminating event is sent
/// to the input observer, or until it has no observers and there
/// are no strong references to it.
///
/// - parameters:
/// - disposable: An optional disposable to associate with the signal, and
/// to be disposed of when the signal terminates.
///
/// - returns: A tuple of `output: Signal`, the output end of the pipe,
/// and `input: Observer`, the input end of the pipe.
public static func pipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) {
var observer: Observer!
let signal = self.init { innerObserver in
observer = innerObserver
return disposable
}
return (signal, observer)
}
/// Observe the Signal by sending any future events to the given observer.
///
/// - note: If the Signal has already terminated, the observer will
/// immediately receive an `interrupted` event.
///
/// - parameters:
/// - observer: An observer to forward the events to.
///
/// - returns: A `Disposable` which can be used to disconnect the observer,
/// or `nil` if the signal has already terminated.
@discardableResult
public func observe(_ observer: Observer) -> Disposable? {
var token: RemovalToken?
updateLock.lock()
if case let .alive(snapshot) = state {
var observers = snapshot.observers
token = observers.insert(observer)
state = .alive(AliveState(observers: observers, retaining: self))
}
updateLock.unlock()
if let token = token {
return ActionDisposable { [weak self] in
if let s = self {
s.updateLock.lock()
if case let .alive(snapshot) = s.state {
var observers = snapshot.observers
observers.remove(using: token)
// Ensure the old signal state snapshot does not deinitialize before
// `updateLock` is released. Otherwise, it might result in a
// deadlock in cases where a `Signal` legitimately receives terminal
// events recursively as a result of the deinitialization of the
// snapshot.
withExtendedLifetime(snapshot) {
s.state = .alive(AliveState(observers: observers,
retaining: observers.isEmpty ? nil : self))
s.updateLock.unlock()
}
} else {
s.updateLock.unlock()
}
}
}
} else {
observer.sendInterrupted()
return nil
}
}
}
/// The state of a `Signal`.
///
/// `SignalState` is guaranteed to be laid out as a tagged pointer by the Swift
/// compiler in the support targets of the Swift 3.0.1 ABI.
///
/// The Swift compiler has also an optimization for enums with payloads that are
/// all reference counted, and at most one no-payload case.
private enum SignalState<Value, Error: Swift.Error> {
/// The `Signal` is alive.
case alive(AliveState<Value, Error>)
/// The `Signal` has received a termination event, and is about to be
/// terminated.
case terminating(TerminatingState<Value, Error>)
/// The `Signal` has terminated.
case terminated
}
// As the amount of state would definitely span over a cache line,
// `AliveState` and `TerminatingState` is set to be a reference type so
// that we can atomically update the reference instead.
//
// Note that in-place mutation should not be introduced to `AliveState` and
// `TerminatingState`. Copy the states and create a new instance.
/// The state of a `Signal` that is alive. It contains a bag of observers and
/// an optional self-retaining reference.
private final class AliveState<Value, Error: Swift.Error> {
/// The observers of the `Signal`.
fileprivate let observers: Bag<Signal<Value, Error>.Observer>
/// A self-retaining reference. It is set when there are one or more active
/// observers.
fileprivate let retaining: Signal<Value, Error>?
/// Create an alive state.
///
/// - parameters:
/// - observers: The latest bag of observers.
/// - retaining: The self-retaining reference of the `Signal`, if necessary.
init(observers: Bag<Signal<Value, Error>.Observer> = Bag(), retaining: Signal<Value, Error>? = nil) {
self.observers = observers
self.retaining = retaining
}
}
/// The state of a terminating `Signal`. It contains a bag of observers and the
/// termination event.
private final class TerminatingState<Value, Error: Swift.Error> {
/// The observers of the `Signal`.
fileprivate let observers: Bag<Signal<Value, Error>.Observer>
/// The termination event.
fileprivate let event: Event<Value, Error>
/// Create a terminating state.
///
/// - parameters:
/// - observers: The latest bag of observers.
/// - event: The termination event.
init(observers: Bag<Signal<Value, Error>.Observer>, event: Event<Value, Error>) {
self.observers = observers
self.event = event
}
}
/// A protocol used to constraint `Signal` operators.
public protocol SignalProtocol {
/// The type of values being sent on the signal.
associatedtype Value
/// The type of error that can occur on the signal. If errors aren't
/// possible then `NoError` can be used.
associatedtype Error: Swift.Error
/// Extracts a signal from the receiver.
var signal: Signal<Value, Error> { get }
/// Observes the Signal by sending any future events to the given observer.
@discardableResult
func observe(_ observer: Signal<Value, Error>.Observer) -> Disposable?
}
extension Signal: SignalProtocol {
public var signal: Signal {
return self
}
}
extension SignalProtocol {
/// Convenience override for observe(_:) to allow trailing-closure style
/// invocations.
///
/// - parameters:
/// - action: A closure that will accept an event of the signal
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observe(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observe the `Signal` by invoking the given callback when `value` or
/// `failed` event are received.
///
/// - parameters:
/// - result: A closure that accepts instance of `Result<Value, Error>`
/// enum that contains either a `.success(Value)` or
/// `.failure<Error>` case.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable? {
return observe(
Observer(
value: { result(.success($0)) },
failed: { result(.failure($0)) }
)
)
}
/// Observe the `Signal` by invoking the given callback when a `completed`
/// event is received.
///
/// - parameters:
/// - completed: A closure that is called when `completed` event is
/// received.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeCompleted(_ completed: @escaping () -> Void) -> Disposable? {
return observe(Observer(completed: completed))
}
/// Observe the `Signal` by invoking the given callback when a `failed`
/// event is received.
///
/// - parameters:
/// - error: A closure that is called when failed event is received. It
/// accepts an error parameter.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
@discardableResult
public func observeFailed(_ error: @escaping (Error) -> Void) -> Disposable? {
return observe(Observer(failed: error))
}
/// Observe the `Signal` by invoking the given callback when an
/// `interrupted` event is received. If the Signal has already terminated,
/// the callback will be invoked immediately.
///
/// - parameters:
/// - interrupted: A closure that is invoked when `interrupted` event is
/// received
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeInterrupted(_ interrupted: @escaping () -> Void) -> Disposable? {
return observe(Observer(interrupted: interrupted))
}
}
extension SignalProtocol where Error == NoError {
/// Observe the Signal by invoking the given callback when `value` events are
/// received.
///
/// - parameters:
/// - value: A closure that accepts a value when `value` event is received.
///
/// - returns: An optional `Disposable` which can be used to stop the
/// invocation of the callback. Disposing of the Disposable will
/// have no effect on the Signal itself.
@discardableResult
public func observeValues(_ value: @escaping (Value) -> Void) -> Disposable? {
return observe(Observer(value: value))
}
}
extension SignalProtocol {
/// Map each value in the signal to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new value.
///
/// - returns: A signal that will send new values.
public func map<U>(_ transform: @escaping (Value) -> U) -> Signal<U, Error> {
return Signal { observer in
return self.observe { event in
observer.action(event.map(transform))
}
}
}
/// Map errors in the signal to a new error.
///
/// - parameters:
/// - transform: A closure that accepts current error object and returns
/// a new type of error object.
///
/// - returns: A signal that will send new type of errors.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
observer.action(event.mapError(transform))
}
}
}
/// Maps each value in the signal to a new value, lazily evaluating the
/// supplied transformation on the specified scheduler.
///
/// - important: Unlike `map`, there is not a 1-1 mapping between incoming
/// values, and values sent on the returned signal. If
/// `scheduler` has not yet scheduled `transform` for
/// execution, then each new value will replace the last one as
/// the parameter to `transform` once it is finally executed.
///
/// - parameters:
/// - transform: The closure used to obtain the returned value from this
/// signal's underlying value.
///
/// - returns: A signal that sends values obtained using `transform` as this
/// signal sends values.
public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> Signal<U, Error> {
return flatMap(.latest) { value in
return SignalProducer({ transform(value) })
.start(on: scheduler)
}
}
/// Preserve only the values of the signal that pass the given predicate.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether value has passed the test.
///
/// - returns: A signal that will send only the values passing the given
/// predicate.
public func filter(_ predicate: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> Void in
guard let value = event.value else {
observer.action(event)
return
}
if predicate(value) {
observer.send(value: value)
}
}
}
}
/// Applies `transform` to values from `signal` and forwards values with non `nil` results unwrapped.
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new optional value.
///
/// - returns: A signal that will send new values, that are non `nil` after the transformation.
public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> Signal<U, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> Void in
switch event {
case let .value(value):
if let mapped = transform(value) {
observer.send(value: mapped)
}
case let .failed(error):
observer.send(error: error)
case .completed:
observer.sendCompleted()
case .interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalProtocol where Value: OptionalProtocol {
/// Unwrap non-`nil` values and forward them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A signal that sends only non-nil values.
public func skipNil() -> Signal<Value.Wrapped, Error> {
return filter { $0.optional != nil }.map { $0.optional! }
}
}
extension SignalProtocol {
/// Take up to `n` values from the signal and then complete.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A signal that will yield the first `count` values from `self`
public func take(first count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
observer.sendCompleted()
return nil
}
var taken = 0
return self.observe { event in
guard let value = event.value else {
observer.action(event)
return
}
if taken < count {
taken += 1
observer.send(value: value)
}
if taken == count {
observer.sendCompleted()
}
}
}
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(_ value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the
/// result of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepingCapacity: true)
}
}
extension SignalProtocol {
/// Collect all values sent by the signal then forward them as a single
/// array and complete.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A signal that will yield an array of values when `self`
/// completes.
public func collect() -> Signal<[Value], Error> {
return collect { _,_ in false }
}
/// Collect at most `count` values from `self`, forward them as a single
/// array and complete.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - precondition: `count` should be greater than zero.
///
public func collect(count: Int) -> Signal<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
/// Collect values that pass the given predicate then forward them as a
/// single array and complete.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if were not
/// collected any values will sent an empty array of values.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .observeValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 3)
/// observer.send(value: 4)
/// observer.send(value: 7)
/// observer.send(value: 1)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`value`) is included in `values` and will be the end of
/// the current array of values if the predicate returns
/// `true`.
///
/// - returns: A signal that collects values passing the predicate and, when
/// `self` completes, forwards them as a single array and
/// complets.
public func collect(_ predicate: @escaping (_ values: [Value]) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .value(value):
state.append(value)
if predicate(state.values) {
observer.send(value: state.values)
state.flush()
}
case .completed:
if !state.isEmpty {
observer.send(value: state.values)
}
observer.sendCompleted()
case let .failed(error):
observer.send(error: error)
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Repeatedly collect an array of values up to a matching `value` value.
/// Then forward them as single array and wait for value events.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not match `predicate`. Alternatively, if no
/// values were collected an empty array will be sent.
///
/// ````
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values, value in value == 7 }
/// .observeValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 1)
/// observer.send(value: 7)
/// observer.send(value: 7)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - predicate: Predicate to match when values should be sent (returning
/// `true`) or alternatively when they should be collected
/// (where it should return `false`). The most recent value
/// (`value`) is not included in `values` and will be the
/// start of the next array of values if the predicate
/// returns `true`.
///
/// - returns: A signal that will yield an array of values based on a
/// predicate which matches the values collected and the next
/// value.
public func collect(_ predicate: @escaping (_ values: [Value], _ value: Value) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .value(value):
if predicate(state.values, value) {
observer.send(value: state.values)
state.flush()
}
state.append(value)
case .completed:
if !state.isEmpty {
observer.send(value: state.values)
}
observer.sendCompleted()
case let .failed(error):
observer.send(error: error)
case .interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal that will yield `self` values on provided scheduler.
public func observe(on scheduler: Scheduler) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
scheduler.schedule {
observer.action(event)
}
}
}
}
}
private final class CombineLatestState<Value> {
var latestValue: Value?
var isCompleted = false
}
extension SignalProtocol {
private func observeWithStates<U>(_ signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ observer: Signal<(), Error>.Observer) -> Disposable? {
return self.observe { event in
switch event {
case let .value(value):
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
observer.send(value: ())
}
lock.unlock()
case let .failed(error):
observer.send(error: error)
case .completed:
lock.lock()
signalState.isCompleted = true
if otherState.isCompleted {
observer.sendCompleted()
}
lock.unlock()
case .interrupted:
observer.sendInterrupted()
}
}
}
/// Combine the latest value of the receiver with the latest value from the
/// given signal.
///
/// - note: The returned signal will not send a value until both inputs have
/// sent at least one value each.
///
/// - note: If either signal is interrupted, the returned signal will also
/// be interrupted.
///
/// - note: The returned signal will not complete until both inputs
/// complete.
///
/// - parameters:
/// - otherSignal: A signal to combine `self`'s value with.
///
/// - returns: A signal that will yield a tuple containing values of `self`
/// and given signal.
public func combineLatest<U>(with other: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.reactivecocoa.ReactiveSwift.combineLatestWith"
let signalState = CombineLatestState<Value>()
let otherState = CombineLatestState<U>()
let onBothValue = {
observer.send(value: (signalState.latestValue!, otherState.latestValue!))
}
let observer = Signal<(), Error>.Observer(value: onBothValue, failed: observer.send(error:), completed: observer.sendCompleted, interrupted: observer.sendInterrupted)
let disposable = CompositeDisposable()
disposable += self.observeWithStates(signalState, otherState, lock, observer)
disposable += other.observeWithStates(otherState, signalState, lock, observer)
return disposable
}
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: failed and `interrupted` events are always scheduled
/// immediately.
///
/// - parameters:
/// - interval: Interval to delay `value` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A signal that will delay `value` and `completed` events and
/// will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
return self.observe { event in
switch event {
case .failed, .interrupted:
scheduler.schedule {
observer.action(event)
}
case .value, .completed:
let date = scheduler.currentDate.addingTimeInterval(interval)
scheduler.schedule(after: date) {
observer.action(event)
}
}
}