This repository has been archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Signal.swift
2259 lines (2012 loc) · 82.6 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 Dispatch
/// 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, Never 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> {
/// The `Signal` core which manages the event stream.
///
/// A `Signal` is the externally retained shell of the `Signal` core. The separation
/// enables an explicit metric for the `Signal` self-disposal in case of having no
/// observer and no external retain.
///
/// `Signal` ownership graph from the perspective of an operator.
/// Note that there is no circular strong reference in the graph.
/// ```
/// ------------ -------------- --------
/// | | | endObserve | | |
/// | | <~~ weak ~~~ | disposable | <== strong === | |
/// | | -------------- | | ... downstream(s)
/// | Upstream | ------------ | |
/// | Core | === strong ==> | Observer | === strong ==> | Core |
/// ------------ ===\\ ------------ -------- ===\\
/// \\ ------------------ ^^ \\
/// \\ | Signal (shell) | === strong ==// \\
/// \\ ------------------ \\
/// || strong || strong
/// vv vv
/// ------------------- -------------------
/// | Other observers | | Other observers |
/// ------------------- -------------------
/// ```
private let core: Core
private final class Core {
/// The disposable associated with the signal.
///
/// Disposing of `disposable` is assumed to remove the generator
/// observer from its attached `Signal`, so that the generator observer
/// as the last +1 retain of the `Signal` core may deinitialize.
private let disposable: CompositeDisposable
/// The state of the signal.
private var state: State
/// Used to ensure that all state accesses are serialized.
private let stateLock: Lock
/// Used to ensure that events are serialized during delivery to observers.
private let sendLock: Lock
fileprivate init(_ generator: (Observer, Lifetime) -> Void) {
state = .alive(Bag(), hasDeinitialized: false)
stateLock = Lock.make()
sendLock = Lock.make()
disposable = CompositeDisposable()
// The generator observer retains the `Signal` core.
generator(Observer(action: self.send, interruptsOnDeinit: true), Lifetime(disposable))
}
private func send(_ event: Event) {
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`.
self.stateLock.lock()
if case let .alive(observers, _) = state {
self.state = .terminating(observers, .init(event))
self.stateLock.unlock()
} else {
self.stateLock.unlock()
}
tryToCommitTermination()
} else {
self.sendLock.lock()
self.stateLock.lock()
if case let .alive(observers, _) = self.state {
self.stateLock.unlock()
for observer in observers {
observer.send(event)
}
} else {
self.stateLock.unlock()
}
self.sendLock.unlock()
// Check if the status has been bumped to `terminating` due to a
// terminal event being sent concurrently or recursively.
//
// The check is deliberately made outside of the `sendLock` so that it
// covers also any potential concurrent terminal event in one shot.
//
// Related PR:
// https://github.com/ReactiveCocoa/ReactiveSwift/pull/112
//
// While calling `tryToCommitTermination` is sufficient, this is a fast
// path for the recurring value delivery.
//
// Note that this cannot be `try` since any concurrent observer bag
// manipulation might then cause the terminating state being missed.
stateLock.lock()
if case .terminating = state {
stateLock.unlock()
tryToCommitTermination()
} else {
stateLock.unlock()
}
}
}
/// Observe the Signal by sending any future events to the given observer.
///
/// - 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.
fileprivate func observe(_ observer: Observer) -> Disposable? {
var token: Bag<Observer>.Token?
stateLock.lock()
if case let .alive(observers, hasDeinitialized) = state {
var newObservers = observers
token = newObservers.insert(observer)
self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized)
}
stateLock.unlock()
if let token = token {
return AnyDisposable { [weak self] in
self?.removeObserver(with: token)
}
} else {
observer.sendInterrupted()
return nil
}
}
/// Remove the observer associated with the given token.
///
/// - parameters:
/// - token: The token of the observer to remove.
private func removeObserver(with token: Bag<Observer>.Token) {
stateLock.lock()
if case let .alive(observers, hasDeinitialized) = state {
var newObservers = observers
let observer = newObservers.remove(using: token)
self.state = .alive(newObservers, hasDeinitialized: hasDeinitialized)
// Ensure `observer` is deallocated after `stateLock` is
// released to avoid deadlocks.
withExtendedLifetime(observer) {
// Start the disposal of the `Signal` core if the `Signal` has
// deinitialized and there is no active observer.
tryToDisposeSilentlyIfQualified(unlocking: stateLock)
}
} else {
stateLock.unlock()
}
}
/// Try to commit the termination, or in other words transition the signal from a
/// terminating state to a terminated state.
///
/// It fails gracefully if the signal is alive or has terminated. Calling this
/// method as a result of a false positive `terminating` check is permitted.
///
/// - precondition: `stateLock` must not be acquired by the caller.
private func tryToCommitTermination() {
// Acquire `stateLock`. If the termination has still not yet been
// handled, take it over and bump the status to `terminated`.
stateLock.lock()
if case let .terminating(observers, terminationKind) = state {
// Try to acquire the `sendLock`, and fail gracefully since the current
// lock holder would attempt to commit after it is done anyway.
if sendLock.try() {
state = .terminated
stateLock.unlock()
if let event = terminationKind.materialize() {
for observer in observers {
observer.send(event)
}
}
sendLock.unlock()
disposable.dispose()
return
}
}
stateLock.unlock()
}
/// Try to dispose of the signal silently if the `Signal` has deinitialized and
/// has no observer.
///
/// It fails gracefully if the signal is terminating or terminated, has one or
/// more observers, or has not deinitialized.
///
/// - precondition: `stateLock` must have been acquired by the caller.
///
/// - parameters:
/// - stateLock: The `stateLock` acquired by the caller.
private func tryToDisposeSilentlyIfQualified(unlocking stateLock: Lock) {
assert(!stateLock.try(), "Calling `unconditionallyTerminate` without acquiring `stateLock`.")
if case let .alive(observers, true) = state, observers.isEmpty {
// Transition to `terminated` directly only if there is no event delivery
// on going.
if sendLock.try() {
self.state = .terminated
stateLock.unlock()
sendLock.unlock()
disposable.dispose()
return
}
self.state = .terminating(Bag(), .silent)
stateLock.unlock()
tryToCommitTermination()
return
}
stateLock.unlock()
}
/// Acknowledge the deinitialization of the `Signal`.
fileprivate func signalDidDeinitialize() {
stateLock.lock()
// Mark the `Signal` has now deinitialized.
if case let .alive(observers, false) = state {
state = .alive(observers, hasDeinitialized: true)
}
// Attempt to start the disposal of the signal if it has no active observer.
tryToDisposeSilentlyIfQualified(unlocking: stateLock)
}
deinit {
disposable.dispose()
}
}
/// 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, Lifetime) -> Void) {
core = Core(generator)
}
/// 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? {
return core.observe(observer)
}
deinit {
core.signalDidDeinitialize()
}
/// 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 State {
// `TerminationKind` is constantly pointer-size large to keep `Signal.Core`
// allocation size independent of the actual `Value` and `Error` types.
enum TerminationKind {
case completed
case interrupted
case failed(Swift.Error)
case silent
init(_ event: Event) {
switch event {
case .value:
fatalError()
case .interrupted:
self = .interrupted
case let .failed(error):
self = .failed(error)
case .completed:
self = .completed
}
}
func materialize() -> Event? {
switch self {
case .completed:
return .completed
case .interrupted:
return .interrupted
case let .failed(error):
return .failed(error as! Error)
case .silent:
return nil
}
}
}
/// The `Signal` is alive.
case alive(Bag<Observer>, hasDeinitialized: Bool)
/// The `Signal` has received a termination event, and is about to be
/// terminated.
case terminating(Bag<Observer>, TerminationKind)
/// The `Signal` has terminated.
case terminated
}
}
extension Signal {
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { observer, lifetime in
// If `observer` deinitializes, the `Signal` would interrupt which is
// undesirable for `Signal.never`.
lifetime.observeEnded { _ = observer }
}
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer, _ in
observer.sendCompleted()
}
}
/// 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 2-tuple of the output end of the pipe as `Signal`, and the input end
/// of the pipe as `Signal.Observer`.
public static func pipe(disposable: Disposable? = nil) -> (output: Signal, input: Observer) {
var observer: Observer!
let signal = self.init { innerObserver, lifetime in
observer = innerObserver
lifetime += disposable
}
return (signal, observer)
}
}
public protocol SignalProtocol: class {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The materialized `self`.
var signal: Signal<Value, Error> { get }
}
extension Signal: SignalProtocol {
public var signal: Signal<Value, Error> {
return self
}
}
extension Signal: SignalProducerConvertible {
public var producer: SignalProducer<Value, Error> {
return SignalProducer(self)
}
}
extension Signal {
/// Observe `self` for all events being emitted.
///
/// - note: If `self` has terminated, the closure would be invoked with an
/// `interrupted` event immediately.
///
/// - parameters:
/// - action: A closure to be invoked with every event from `self`.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observe(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observe `self` for all values being emitted, and if any, the failure.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`, or the propagated
/// error should any `failed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable? {
return observe(
Observer(
value: { action(.success($0)) },
failed: { action(.failure($0)) }
)
)
}
/// Observe `self` for its completion.
///
/// - parameters:
/// - action: A closure to be invoked when a `completed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeCompleted(_ action: @escaping () -> Void) -> Disposable? {
return observe(Observer(completed: action))
}
/// Observe `self` for its failure.
///
/// - parameters:
/// - action: A closure to be invoked with the propagated error, should any
/// `failed` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeFailed(_ action: @escaping (Error) -> Void) -> Disposable? {
return observe(Observer(failed: action))
}
/// Observe `self` for its interruption.
///
/// - note: If `self` has terminated, the closure would be invoked immediately.
///
/// - parameters:
/// - action: A closure to be invoked when an `interrupted` event is emitted.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeInterrupted(_ action: @escaping () -> Void) -> Disposable? {
return observe(Observer(interrupted: action))
}
}
extension Signal where Error == Never {
/// Observe `self` for all values being emitted.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`.
///
/// - returns: A disposable to detach `action` from `self`. `nil` if `self` has
/// terminated.
@discardableResult
public func observeValues(_ action: @escaping (Value) -> Void) -> Disposable? {
return observe(Observer(value: action))
}
}
extension Signal {
/// Perform an action upon every event from `self`. The action may generate zero or
/// more events.
///
/// - precondition: The action must be synchronous.
///
/// - parameters:
/// - transform: A closure that creates the said action from the given event
/// closure.
///
/// - returns: A signal that forwards events yielded by the action.
internal func flatMapEvent<U, E>(_ transform: @escaping Event.Transformation<U, E>) -> Signal<U, E> {
return Signal<U, E> { output, lifetime in
// Create an input sink whose events would go through the given
// event transformation, and have the resulting events propagated
// to the resulting `Signal`.
let input = transform(output.send, lifetime)
lifetime += self.observe(input)
}
}
/// 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 flatMapEvent(Signal.Event.map(transform))
}
/// Map each value in the signal to a new constant value.
///
/// - parameters:
/// - value: A new value.
///
/// - returns: A signal that will send new values.
public func map<U>(value: U) -> Signal<U, Error> {
return map { _ in value }
}
/// Map each value in the signal to a new value by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the signal's `Value` type.
///
/// - returns: A signal that will send new values.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> Signal<U, Error> {
return map { $0[keyPath: keyPath] }
}
/// 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 flatMapEvent(Signal.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 flatMapEvent(Signal.Event.lazyMap(on: scheduler, transform: transform))
}
/// Preserve only values which pass the given closure.
///
/// - parameters:
/// - isIncluded: A closure to determine whether a value from `self` should be
/// included in the returned `Signal`.
///
/// - returns: A signal that forwards the values passing the given closure.
public func filter(_ isIncluded: @escaping (Value) -> Bool) -> Signal<Value, Error> {
return flatMapEvent(Signal.Event.filter(isIncluded))
}
/// 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 flatMapEvent(Signal.Event.filterMap(transform))
}
}
extension Signal 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 flatMapEvent(Signal.Event.skipNil)
}
}
extension Signal {
/// 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)
guard count >= 1 else { return .empty }
return flatMapEvent(Signal.Event.take(first: count))
}
/// 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 flatMapEvent(Signal.Event.collect)
}
/// 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> {
return flatMapEvent(Signal.Event.collect(count: count))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the returned `Signal`.
///
/// ````
/// let (signal, observer) = Signal<Int, Never>.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:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is included in the collected values.
///
/// - returns: A signal of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collectedValues: [Value]) -> Bool) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the returned `Signal`.
///
/// ````
/// let (signal, observer) = Signal<Int, Never>.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:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is **not** included in the collected values, and is included when
/// the next value is received.
///
/// - returns: A signal of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Forward the latest values on `scheduler` every `interval`.
///
/// - note: If `self` terminates while values are being accumulated,
/// the behaviour will be determined by `discardWhenCompleted`.
/// If `true`, the values will be discarded and the returned signal
/// will terminate immediately.
/// If `false`, that values will be delivered at the next interval.
///
/// - parameters:
/// - interval: A repetition interval.
/// - scheduler: A scheduler to send values on.
/// - skipEmpty: Whether empty arrays should be sent if no values were
/// accumulated during the interval.
/// - discardWhenCompleted: A boolean to indicate if the latest unsent
/// values should be discarded on completion.
///
/// - returns: A signal that sends all values that are sent from `self` at
/// `interval` seconds apart.
public func collect(every interval: DispatchTimeInterval, on scheduler: DateScheduler, skipEmpty: Bool = false, discardWhenCompleted: Bool = true) -> Signal<[Value], Error> {
return flatMapEvent(Signal.Event.collect(every: interval, on: scheduler, skipEmpty: skipEmpty, discardWhenCompleted: discardWhenCompleted))
}
/// 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 flatMapEvent(Signal.Event.observe(on: scheduler))
}
}
extension Signal {
/// 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.combineLatest(self, other)
}
/// Merge the given signal into a single `Signal` that will emit all
/// values from both of them, and complete when all of them have completed.
///
/// - parameters:
/// - other: A signal to merge `self`'s value with.
///
/// - returns: A signal that sends all values of `self` and given signal.
public func merge(with other: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal.merge(self, other)
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: failed and `interrupted` events are always scheduled
/// immediately.
///
/// - precondition: `interval` must be non-negative number.
///
/// - 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> {
return flatMapEvent(Signal.Event.delay(interval, on: scheduler))
}
/// Skip first `count` number of values then act as usual.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A signal that will skip the first `count` values, then
/// forward everything afterward.
public func skip(first count: Int) -> Signal<Value, Error> {
guard count != 0 else { return self }
return flatMapEvent(Signal.Event.skip(first: count))
}
/// Treat all Events from `self` as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad”.
///
/// - note: When a Completed or Failed event is received, the resulting
/// signal will send the Event itself and then complete. When an
/// Interrupted event is received, the resulting signal will send
/// the Event itself and then interrupt.
///
/// - returns: A signal that sends events as its values.
public func materialize() -> Signal<Event, Never> {
return flatMapEvent(Signal.Event.materialize)
}
/// Treats all Results from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Results “into the monad.”
///
/// - note: When a Failed event is received, the resulting producer will
/// send the `Result.failure` itself and then complete.
///
/// - returns: A producer that sends results as its values.
public func materializeResults() -> Signal<Result<Value, Error>, Never> {
return flatMapEvent(Signal.Event.materializeResults)
}
}
extension Signal where Value: EventProtocol, Error == Never {
/// Translate a signal of `Event` _values_ into a signal of those events
/// themselves.
///
/// - returns: A signal that sends values carried by `self` events.
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return flatMapEvent(Signal.Event.dematerialize)
}
}
extension Signal where Value: ResultProtocol, Error == Never {
/// Translate a signal of `Result` _values_ into a signal of those events
/// themselves.
///
/// - returns: A signal that sends values carried by `self` events.
public func dematerializeResults() -> Signal<Value.Success, Value.Failure> {
return flatMapEvent(Signal.Event.dematerializeResults)
}
}
extension Signal {
/// Inject side effects to be performed upon the specified signal events.
///
/// - parameters:
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - failed: A closure that accepts error object and is invoked for
/// failed event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
/// - value: A closure that accepts a value from `value` event.
///
/// - returns: A signal with attached side-effects for given event cases.
public func on(
event: ((Event) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil,
value: ((Value) -> Void)? = nil
) -> Signal<Value, Error> {
return Signal { observer, lifetime in
if let action = disposed {
lifetime.observeEnded(action)
}
lifetime += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .value(v):
value?(v)
case let .failed(error):
failed?(error)
case .completed:
completed?()
case .interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.send(receivedEvent)
}
}
}
}
private struct SampleState<Value> {
var latestValue: Value?
var isSignalCompleted: Bool = false
var isSamplerCompleted: Bool = false
}
extension Signal {
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when`sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A signal that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A signal that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input signals have completed, or interrupt if
/// either input signal is interrupted.
public func sample<T>(with sampler: Signal<T, Never>) -> Signal<(Value, T), Error> {
return Signal<(Value, T), Error> { observer, lifetime in
let state = Atomic(SampleState<Value>())
lifetime += self.observe { event in
switch event {
case let .value(value):
state.modify {