forked from ReactiveCocoa/ReactiveSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SignalProducer.swift
3016 lines (2747 loc) · 128 KB
/
SignalProducer.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 Dispatch
import Foundation
/// A SignalProducer creates Signals that can produce values of type `Value`
/// and/or fail with errors of type `Error`. If no failure should be possible,
/// `Never` can be specified for `Error`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of `start()` will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of `start()`, different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<Value, Error: Swift.Error> {
public typealias ProducedSignal = Signal<Value, Error>
/// `core` is the actual implementation for this `SignalProducer`. It is responsible
/// of:
///
/// 1. handling the single-observer `start`; and
/// 2. building `Signal`s on demand via its `makeInstance()` method, which produces a
/// `Signal` with the associated side effect and interrupt handle.
fileprivate let core: SignalProducerCore<Value, Error>
/// Convert an entity into its equivalent representation as `SignalProducer`.
///
/// - parameters:
/// - base: The entity to convert from.
public init<T: SignalProducerConvertible>(_ base: T) where T.Value == Value, T.Error == Error {
self = base.producer
}
/// Initializes a `SignalProducer` that will emit the same events as the
/// given signal.
///
/// If the Disposable returned from `start()` is disposed or a terminating
/// event is sent to the observer, the given signal will be disposed.
///
/// - parameters:
/// - signal: A signal to observe after starting the producer.
public init(_ signal: Signal<Value, Error>) {
self.init { observer, lifetime in
lifetime += signal.observe(observer)
}
}
/// Initialize a `SignalProducer` which invokes the supplied starting side
/// effect once upon the creation of every produced `Signal`, or in other
/// words, for every invocation of `startWithSignal(_:)`, `start(_:)` and
/// their convenience shorthands.
///
/// The supplied starting side effect would be given (1) an input `Observer`
/// to emit events to the produced `Signal`; and (2) a `Lifetime` to bind
/// resources to the lifetime of the produced `Signal`.
///
/// The `Lifetime` of a produced `Signal` ends when: (1) a terminal event is
/// sent to the input `Observer`; or (2) when the produced `Signal` is
/// interrupted via the disposable yielded at the starting call.
///
/// - parameters:
/// - startHandler: The starting side effect.
public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, Lifetime) -> Void) {
self.init(SignalCore {
let disposable = CompositeDisposable()
let (signal, observer) = Signal<Value, Error>.pipe(disposable: disposable)
let observerDidSetup = { startHandler(observer, Lifetime(disposable)) }
let interruptHandle = AnyDisposable(observer.sendInterrupted)
return SignalProducerCore.Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: interruptHandle)
})
}
/// Create a SignalProducer.
///
/// - parameters:
/// - core: The `SignalProducer` core.
internal init(_ core: SignalProducerCore<Value, Error>) {
self.core = core
}
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a `Signal` that immediately sends one value, then
/// completes.
///
/// This initializer differs from `init(value:)` in that its sole `value`
/// event is constructed lazily by invoking the supplied `action` when
/// the `SignalProducer` is started.
///
/// - parameters:
/// - action: A action that yields a value to be sent by the `Signal` as
/// a `value` event.
public init(_ action: @escaping () -> Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: action())
observer.sendCompleted()
})
}
/// Create a `SignalProducer` that will attempt the given operation once for
/// each invocation of `start()`.
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - action: A closure that returns instance of `Result`.
public init(_ action: @escaping () -> Result<Value, Error>) {
self.init(GeneratorCore { observer, _ in
switch action() {
case let .success(value):
observer.send(value: value)
observer.sendCompleted()
case let .failure(error):
observer.send(error: error)
}
})
}
/// Creates a producer for a `Signal` that will immediately fail with the
/// given error.
///
/// - parameters:
/// - error: An error that should be sent by the `Signal` in a `failed`
/// event.
public init(error: Error) {
self.init(GeneratorCore { observer, _ in observer.send(error: error) })
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately fail, depending on the given Result.
///
/// - parameters:
/// - result: A `Result` instance that will send either `value` event if
/// `result` is `success`ful or `failed` event if `result` is a
/// `failure`.
public init(result: Result<Value, Error>) {
switch result {
case let .success(value):
self.init(value: value)
case let .failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
/// A producer for a Signal that immediately completes without sending any values.
public static var empty: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendCompleted() })
}
/// A producer for a Signal that immediately interrupts when started, without
/// sending any values.
internal static var interrupted: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendInterrupted() })
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { observer, lifetime in
lifetime.observeEnded { _ = observer }
}
}
/// Create a `Signal` from `self`, pass it into the given closure, and start the
/// associated work on the produced `Signal` as the closure returns.
///
/// - parameters:
/// - setup: A closure to be invoked before the work associated with the produced
/// `Signal` commences. Both the produced `Signal` and an interrupt handle
/// of the signal would be passed to the closure.
/// - returns: The return value of the given setup closure.
@discardableResult
public func startWithSignal<Result>(_ setup: (_ signal: Signal<Value, Error>, _ interruptHandle: Disposable) -> Result) -> Result {
let instance = core.makeInstance()
let result = setup(instance.signal, instance.interruptHandle)
if !instance.interruptHandle.isDisposed {
instance.observerDidSetup()
}
return result
}
}
/// `SignalProducerCore` is the actual implementation of a `SignalProducer`.
///
/// While `SignalProducerCore` still requires all subclasses to be able to produce
/// instances of `Signal`s, the abstraction enables room of optimization for common
/// compositional and single-observer use cases.
internal class SignalProducerCore<Value, Error: Swift.Error> {
/// `Instance` represents an instance of `Signal` created from a
/// `SignalProducer`. In addition to the `Signal` itself, it includes also the
/// starting side effect and an interrupt handle for this particular instance.
///
/// It is the responsibility of the `Instance` consumer to ensure the
/// starting side effect is invoked exactly once, and is invoked after observations
/// has properly setup.
struct Instance {
let signal: Signal<Value, Error>
let observerDidSetup: () -> Void
let interruptHandle: Disposable
}
func makeInstance() -> Instance {
fatalError()
}
/// Start the producer with an observer created by the given generator.
///
/// The created observer **must** manaully dispose of the given upstream interrupt
/// handle iff it performs any event transformation that might result in a terminal
/// event.
///
/// - parameters:
/// - generator: The closure to generate an observer.
///
/// - returns: A disposable to interrupt the started producer instance.
@discardableResult
func start(_ generator: (_ upstreamInterruptHandle: Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
fatalError()
}
/// 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 producer that forwards events yielded by the action.
internal func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore(source: self, transform: transform))
}
}
private final class SignalCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let _make: () -> Instance
init(_ action: @escaping () -> Instance) {
self._make = action
}
@discardableResult
override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
let instance = makeInstance()
instance.signal.observe(generator(instance.interruptHandle))
instance.observerDidSetup()
return instance.interruptHandle
}
override func makeInstance() -> Instance {
return _make()
}
}
/// `TransformerCore` composes event transforms, and is intended to back synchronous
/// `SignalProducer` operators in general via the core-level operator `Core.flatMapEvent`.
///
/// It takes advantage of the deferred, single-observer nature of SignalProducer. For
/// example, when we do:
///
/// ```
/// upstream.map(transform).compactMap(filteringTransform).start()
/// ```
///
/// It is contractually guaranteed that these operators would always end up producing a
/// chain of streams, each with a _single and persistent_ observer to its upstream. The
/// multicasting & detaching capabilities of Signal is useless in these scenarios.
///
/// So TransformerCore builds on top of this very fact, and composes directly at the
/// level of event transforms, without any `Signal` in between.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class TransformerCore<Value, Error: Swift.Error, SourceValue, SourceError: Swift.Error>: SignalProducerCore<Value, Error> {
private let source: SignalProducerCore<SourceValue, SourceError>
private let transform: Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>
init(source: SignalProducerCore<SourceValue, SourceError>, transform: @escaping Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>) {
self.source = source
self.transform = transform
}
@discardableResult
internal override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Collect all resources related to this transformed producer instance.
let disposables = CompositeDisposable()
source.start { upstreamInterrupter in
// Backpropagate the terminal event, if any, to the upstream.
disposables += upstreamInterrupter
var hasDeliveredTerminalEvent = false
// Generate the output sink that receives transformed output.
let output = generator(disposables)
// Wrap the output sink to enforce the "no event beyond the terminal
// event" contract, and the disposal upon termination.
let wrappedOutput: Signal<Value, Error>.Observer.Action = { event in
if !hasDeliveredTerminalEvent {
output.send(event)
if event.isTerminating {
// Mark that a terminal event has already been
// delivered.
hasDeliveredTerminalEvent = true
// Disposed of all associated resources, and notify
// the upstream too.
disposables.dispose()
}
}
}
// Create an input sink whose events would go through the given
// event transformation, and have the resulting events propagated
// to the output sink above.
let input = transform(wrappedOutput, Lifetime(disposables))
// Return the input sink to the source producer core.
return Signal<SourceValue, SourceError>.Observer(input)
}
// Manual interruption disposes of `disposables`, which in turn notifies
// the event transformation side effects, and the upstream instance.
return disposables
}
internal override func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore<U, E, SourceValue, SourceError>(source: source) { [innerTransform = self.transform] action, lifetime in
return innerTransform(transform(action, lifetime), lifetime)
})
}
internal override func makeInstance() -> Instance {
let disposable = SerialDisposable()
let (signal, observer) = Signal<Value, Error>.pipe(disposable: disposable)
func observerDidSetup() {
start { interrupter in
disposable.inner = interrupter
return observer
}
}
return Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: disposable)
}
}
/// `GeneratorCore` wraps a generator closure that would be invoked upon a produced
/// `Signal` when started. The generator closure is passed only the input observer and the
/// cancel disposable.
///
/// It is intended for constant `SignalProducers`s that synchronously emits all events
/// without escaping the `Observer`.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class GeneratorCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let isDisposable: Bool
private let generator: (Signal<Value, Error>.Observer, Disposable) -> Void
init(isDisposable: Bool = false, _ generator: @escaping (Signal<Value, Error>.Observer, Disposable) -> Void) {
self.isDisposable = isDisposable
self.generator = generator
}
@discardableResult
internal override func start(_ observerGenerator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Object allocation is a considerable overhead. So unless the core is configured
// to be disposable, we would reuse the already-disposed, shared `NopDisposable`.
let d: Disposable = isDisposable ? _SimpleDisposable() : NopDisposable.shared
generator(observerGenerator(d), d)
return d
}
internal override func makeInstance() -> Instance {
let (signal, observer) = Signal<Value, Error>.pipe()
let d = AnyDisposable(observer.sendInterrupted)
return Instance(signal: signal,
observerDidSetup: { self.generator(observer, d) },
interruptHandle: d)
}
}
extension SignalProducer where Error == Never {
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
}
extension SignalProducer where Error == Swift.Error {
/// Create a `SignalProducer` that will attempt the given failable operation once for
/// each invocation of `start()`.
///
/// Upon success, the started producer will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - operation: A failable closure.
public init(_ action: @escaping () throws -> Value) {
self.init {
return Result {
return try action()
}
}
}
}
/// Represents reactive primitives that can be represented by `SignalProducer`.
public protocol SignalProducerConvertible {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The `SignalProducer` representation of `self`.
var producer: SignalProducer<Value, Error> { get }
}
/// A protocol for constraining associated types to `SignalProducer`.
public protocol SignalProducerProtocol {
/// 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 producer: SignalProducer<Value, Error> { get }
}
extension SignalProducer: SignalProducerConvertible, SignalProducerProtocol {
public var producer: SignalProducer {
return self
}
}
extension SignalProducer {
/// Create a `Signal` from `self`, and observe it with the given observer.
///
/// - parameters:
/// - observer: An observer to attach to the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
return core.start { _ in observer }
}
/// Create a `Signal` from `self`, and observe the `Signal` for all events
/// being emitted.
///
/// - parameters:
/// - action: A closure to be invoked with every event from `self`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Signal.Observer(action))
}
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted, and if any, its 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 interrupt the produced `Signal`.
@discardableResult
public func startWithResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable {
return start(
Signal.Observer(
value: { action(.success($0)) },
failed: { action(.failure($0)) }
)
)
}
/// Create a `Signal` from `self`, and observe its completion.
///
/// - parameters:
/// - action: A closure to be invoked when a `completed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithCompleted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(completed: action))
}
/// Create a `Signal` from `self`, and observe its failure.
///
/// - parameters:
/// - action: A closure to be invoked with the propagated error, should any
/// `failed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithFailed(_ action: @escaping (Error) -> Void) -> Disposable {
return start(Signal.Observer(failed: action))
}
/// Create a `Signal` from `self`, and observe its interruption.
///
/// - parameters:
/// - action: A closure to be invoked when an `interrupted` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithInterrupted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(interrupted: action))
}
/// Creates a `Signal` from the producer.
///
/// This is equivalent to `SignalProducer.startWithSignal`, but it has
/// the downside that any values emitted synchronously upon starting will
/// be missed by the observer, because it won't be able to subscribe in time.
/// That's why we don't want this method to be exposed as `public`,
/// but it's useful internally.
internal func startAndRetrieveSignal() -> Signal<Value, Error> {
var result: Signal<Value, Error>!
self.startWithSignal { signal, _ in
result = signal
}
return result
}
/// Create a `Signal` from `self` in the manner described by `startWithSignal`, and
/// put the interrupt handle into the given `CompositeDisposable`.
///
/// - parameters:
/// - lifetime: The `Lifetime` the interrupt handle to be added to.
/// - setup: A closure that accepts the produced `Signal`.
fileprivate func startWithSignal(during lifetime: Lifetime, setup: (Signal<Value, Error>) -> Void) {
startWithSignal { signal, interruptHandle in
lifetime += interruptHandle
setup(signal)
}
}
}
extension SignalProducer where Error == Never {
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted.
///
/// - parameters:
/// - action: A closure to be invoked with values from the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithValues(_ action: @escaping (Value) -> Void) -> Disposable {
return start(Signal.Observer(value: action))
}
}
extension SignalProducer {
/// Lift an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ created `Signal`, just as if the
/// operator had been applied to each `Signal` yielded from `start()`.
///
/// - parameters:
/// - transform: An unary operator to lift.
///
/// - returns: A signal producer that applies signal's operator to every
/// created signal.
public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> {
return SignalProducer<U, F> { observer, lifetime in
self.startWithSignal { signal, interrupter in
lifetime += interrupter
transform(signal).observe(observer)
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The left producer would first be started. When both producers are synchronous this
/// order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
fileprivate func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The right producer would first be started. When both producers are synchronous
/// this order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
fileprivate func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ `Signal` created from the two
/// producers, just as if the operator had been applied to each `Signal`
/// yielded from `start()`.
///
/// - note: starting the returned producer will start the receiver of the
/// operator, which may not be adviseable for some operators.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that operates on two signal producers.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return liftRight(transform)
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>) -> Void) {
b.startWithSignal(during: lifetime) { b in
a.startWithSignal(during: lifetime) { setup($0, b) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>) -> Void) {
c.startWithSignal(during: lifetime) { c in
flattenStart(lifetime, a, b) { setup($0, $1, c) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>) -> Void) {
d.startWithSignal(during: lifetime) { d in
flattenStart(lifetime, a, b, c) { setup($0, $1, $2, d) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>) -> Void) {
e.startWithSignal(during: lifetime) { e in
flattenStart(lifetime, a, b, c, d) { setup($0, $1, $2, $3, e) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>) -> Void) {
f.startWithSignal(during: lifetime) { f in
flattenStart(lifetime, a, b, c, d, e) { setup($0, $1, $2, $3, $4, f) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>) -> Void) {
g.startWithSignal(during: lifetime) { g in
flattenStart(lifetime, a, b, c, d, e, f) { setup($0, $1, $2, $3, $4, $5, g) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>) -> Void) {
h.startWithSignal(during: lifetime) { h in
flattenStart(lifetime, a, b, c, d, e, f, g) { setup($0, $1, $2, $3, $4, $5, $6, h) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>) -> Void) {
i.startWithSignal(during: lifetime) { i in
flattenStart(lifetime, a, b, c, d, e, f, g, h) { setup($0, $1, $2, $3, $4, $5, $6, $7, i) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, J, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>, Signal<J, Error>) -> Void) {
j.startWithSignal(during: lifetime) { j in
flattenStart(lifetime, a, b, c, d, e, f, g, h, i) { setup($0, $1, $2, $3, $4, $5, $6, $7, $8, j) }
}
}
extension SignalProducer {
/// Map each value in the producer to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns a different
/// value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self.`
public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.map(transform))
}
/// Map each value in the producer to a new constant value.
///
/// - parameters:
/// - value: A new value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self`.
public func map<U>(value: U) -> SignalProducer<U, Error> {
return lift { $0.map(value: value) }
}
/// Map each value in the producer to a new value by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the producer's `Value` type.
///
/// - returns: A producer that will send new values.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap { $0[keyPath: keyPath] })
}
/// Map errors in the producer to a new error.
///
/// - parameters:
/// - transform: A closure that accepts an error object and returns a
/// different error.
///
/// - returns: A producer that emits errors of new type.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> {
return core.flatMapEvent(Signal.Event.mapError(transform))
}
/// Maps each value in the producer 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 producer. 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
/// producer's underlying value.
///
/// - returns: A producer that, when started, sends values obtained using
/// `transform` as this producer sends values.
public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.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 produced `Signal`.
///
/// - returns: A producer that, when started, forwards the values passing the given
/// closure.
public func filter(_ isIncluded: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.filter(isIncluded))
}
/// Applies `transform` to values from the producer 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 producer that will send new values, that are non `nil` after the transformation.
public func compactMap<U>(_ transform: @escaping (Value) -> U?) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap(transform))
}
/// Applies `transform` to values from the producer 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 producer that will send new values, that are non `nil` after the transformation.
@available(*, deprecated, renamed: "compactMap")
public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.compactMap(transform))
}
/// Yield the first `count` values from the input producer.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A producer that, when started, will yield the first `count`
/// values from `self`.
public func take(first count: Int) -> SignalProducer<Value, Error> {
guard count >= 1 else { return .interrupted }
return core.flatMapEvent(Signal.Event.take(first: count))
}
/// Yield an array of values when `self` completes.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A producer that, when started, will yield an array of values
/// when `self` completes.
public func collect() -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect)
}
/// Yield an array of values until it reaches a certain count.
///
/// - precondition: `count` must be greater than zero.
///
/// - 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.
///
/// - returns: A producer that, when started, collects at most `count`
/// values from `self`, forwards them as a single array and
/// completes.
public func collect(count: Int) -> SignalProducer<[Value], Error> {
return core.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 produced `Signal`.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, Never>.buffer(1)
///
/// producer
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .startWithValues { print($0) }