forked from ReactiveCocoa/ReactiveCocoa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSignalProducer.swift
1943 lines (1766 loc) · 73.7 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 Foundation
import Result
/// 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,
/// `NoError` 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>
private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> Void
/// 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<S: SignalProtocol>(signal: S) where S.Value == Value, S.Error == Error {
self.init { observer, disposable in
disposable += signal.observe(observer)
}
}
/// Initializes a SignalProducer that will invoke the given closure once for
/// each invocation of `start()`.
///
/// The events that the closure puts into the given observer will become
/// the events sent by the started `Signal` to its observers.
///
/// - note: If the `Disposable` returned from `start()` is disposed or a
/// terminating event is sent to the observer, the given
/// `CompositeDisposable` will be disposed, at which point work
/// should be interrupted and any temporary resources cleaned up.
///
/// - parameters:
/// - startHandler: A closure that accepts observer and a disposable.
public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void) {
self.startHandler = startHandler
}
/// 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 `next`
/// event.
public init(value: Value) {
self.init { observer, disposable in
observer.sendNext(value)
observer.sendCompleted()
}
}
/// 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 { observer, disposable in
observer.sendFailed(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 `next` 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
/// `next` events and then complete.
public init<S: Sequence>(values: S) where S.Iterator.Element == Value {
self.init { observer, disposable in
for value in values {
observer.sendNext(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(values: [ first, second ] + tail)
}
/// A producer for a Signal that will immediately complete without sending
/// any values.
public static var empty: SignalProducer {
return self.init { observer, disposable in
observer.sendCompleted()
}
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { _ in return }
}
/// 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:
/// - operation: A closure that returns instance of `Result`.
///
/// - returns: A `SignalProducer` that will forward `success`ful `result` as
/// `next` event and then complete or `failed` event if `result`
/// is a `failure`.
public static func attempt(_ operation: @escaping () -> Result<Value, Error>) -> SignalProducer {
return self.init { observer, disposable in
operation().analysis(ifSuccess: { value in
observer.sendNext(value)
observer.sendCompleted()
}, ifFailure: { error in
observer.sendFailed(error)
})
}
}
/// Create a Signal from the producer, pass it into the given closure,
/// then start sending events on the Signal when the closure has returned.
///
/// The closure will also receive a disposable which can be used to
/// interrupt the work associated with the signal and immediately send an
/// `interrupted` event.
///
/// - parameters:
/// - setUp: A closure that accepts a `signal` and `interrupter`.
public func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void) {
let (signal, observer) = Signal<Value, Error>.pipe()
// Disposes of the work associated with the SignalProducer and any
// upstream producers.
let producerDisposable = CompositeDisposable()
// Directly disposed of when `start()` or `startWithSignal()` is
// disposed.
let cancelDisposable = ActionDisposable {
observer.sendInterrupted()
producerDisposable.dispose()
}
setup(signal, cancelDisposable)
if cancelDisposable.isDisposed {
return
}
let wrapperObserver: Signal<Value, Error>.Observer = Observer { event in
observer.action(event)
if event.isTerminating {
// Dispose only after notifying the Signal, so disposal
// logic is consistently the last thing to run.
producerDisposable.dispose()
}
}
startHandler(wrapperObserver, producerDisposable)
}
}
public protocol SignalProducerProtocol {
/// The type of values being sent on the producer
associatedtype Value
/// The type of error that can occur on the producer. If errors aren't possible
/// then `NoError` can be used.
associatedtype Error: Swift.Error
/// Extracts a signal producer from the receiver.
var producer: SignalProducer<Value, Error> { get }
/// Initialize a signal
init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void)
/// Creates a Signal from the producer, passes it into the given closure,
/// then starts sending events on the Signal when the closure has returned.
func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void)
}
extension SignalProducer: SignalProducerProtocol {
public var producer: SignalProducer {
return self
}
}
extension SignalProducerProtocol {
/// Create a Signal from the producer, then attach the given observer to
/// the `Signal` as an observer.
///
/// - parameters:
/// - observer: An observer to attach to produced signal.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal and immediately send an
/// `interrupted` event.
@discardableResult
public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
var disposable: Disposable!
startWithSignal { signal, innerDisposable in
signal.observe(observer)
disposable = innerDisposable
}
return disposable
}
/// Convenience override for start(_:) to allow trailing-closure style
/// invocations.
///
/// - parameters:
/// - observerAction: A closure that accepts `Event` sent by the produced
/// signal.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal and immediately send an
/// `interrupted` event.
@discardableResult
public func start(_ observerAction: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Observer(observerAction))
}
/// Create a Signal from the producer, then add an observer to the `Signal`,
/// which will invoke the given callback when `next` or `failed` events are
/// received.
///
/// - parameters:
/// - result: A closure that accepts a `result` that contains a `.success`
/// case for `next` events or `.failure` case for `failed` event.
///
/// - returns: A Disposable which can be used to interrupt the work
/// associated with the Signal, and prevent any future callbacks
/// from being invoked.
@discardableResult
public func startWithResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable {
return start(
Observer(
next: { result(.success($0)) },
failed: { result(.failure($0)) }
)
)
}
/// Create a Signal from the producer, then add exactly one observer to the
/// Signal, which will invoke the given callback when a `completed` event is
/// received.
///
/// - parameters:
/// - completed: A closure that will be envoked when produced signal sends
/// `completed` event.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithCompleted(_ completed: @escaping () -> Void) -> Disposable {
return start(Observer(completed: completed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when a `failed` event
/// is received.
///
/// - parameters:
/// - failed: A closure that accepts an error object.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithFailed(_ failed: @escaping (Error) -> Void) -> Disposable {
return start(Observer(failed: failed))
}
/// Creates a Signal from the producer, then adds exactly one observer to
/// the Signal, which will invoke the given callback when an `interrupted`
/// event is received.
///
/// - parameters:
/// - interrupted: A closure that is invoked when `interrupted` event is
/// received.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the signal.
@discardableResult
public func startWithInterrupted(_ interrupted: @escaping () -> Void) -> Disposable {
return start(Observer(interrupted: interrupted))
}
}
extension SignalProducerProtocol where Error == NoError {
/// Create a Signal from the producer, then add exactly one observer to
/// the Signal, which will invoke the given callback when `next` events are
/// received.
///
/// - parameters:
/// - next: A closure that accepts a value carried by `next` event.
///
/// - returns: A `Disposable` which can be used to interrupt the work
/// associated with the Signal, and prevent any future callbacks
/// from being invoked.
@discardableResult
public func startWithNext(_ next: @escaping (Value) -> Void) -> Disposable {
return start(Observer(next: next))
}
}
extension SignalProducerProtocol {
/// 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 { observer, outerDisposable in
self.startWithSignal { signal, innerDisposable in
outerDisposable += innerDisposable
transform(signal).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)
}
/// Right-associative lifting of a binary signal operator over producers.
/// That is, the argument producer will be started before the receiver. When
/// both producers are synchronous this order can be important depending on
/// the operator to generate correct results.
private func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable += otherDisposable
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Left-associative lifting of a binary signal operator over producers.
/// That is, the receiver will be started before the argument producer. When
/// both producers are synchronous this order can be important depending on
/// the operator to generate correct results.
private func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { otherProducer in
return SignalProducer { observer, outerDisposable in
otherProducer.startWithSignal { otherSignal, otherDisposable in
outerDisposable += otherDisposable
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
transform(signal)(otherSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon a Signal and a
/// SignalProducer 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()`.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that works on `Signal` and returns
/// `SignalProducer`.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (Signal<U, F>) -> SignalProducer<V, G> {
return { otherSignal in
return SignalProducer { observer, outerDisposable in
let (wrapperSignal, otherSignalObserver) = Signal<U, F>.pipe()
// Avoid memory leak caused by the direct use of the given
// signal.
//
// See https://github.com/ReactiveCocoa/ReactiveCocoa/pull/2758
// for the details.
outerDisposable += ActionDisposable {
otherSignalObserver.sendInterrupted()
}
outerDisposable += otherSignal.observe(otherSignalObserver)
self.startWithSignal { signal, disposable in
outerDisposable += disposable
outerDisposable += transform(signal)(wrapperSignal).observe(observer)
}
}
}
}
/// 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 lift { $0.map(transform) }
}
/// 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 lift { $0.mapError(transform) }
}
/// Preserve only the values of the producer that pass the given predicate.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` denoting
/// whether value has passed the test.
///
/// - returns: A producer that, when started, will send only the values
/// passing the given predicate.
public func filter(_ predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.filter(predicate) }
}
/// 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> {
return lift { $0.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 lift { $0.collect() }
}
/// Yield an array of values until it reaches a certain count.
///
/// - precondition: `count` should 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> {
precondition(count > 0)
return lift { $0.collect(count: count) }
}
/// Yield an array of values based on a predicate which matches the values
/// collected.
///
/// - 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 (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
///
/// producer
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .startWithNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(3)
/// observer.sendNext(4)
/// observer.sendNext(7)
/// observer.sendNext(1)
/// observer.sendNext(5)
/// observer.sendNext(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
/// (`next`) is included in `values` and will be the end of
/// the current array of values if the predicate returns
/// `true`.
///
/// - returns: A producer that, when started, 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) -> SignalProducer<[Value], Error> {
return lift { $0.collect(predicate) }
}
/// Yield an array of values based on a predicate which matches the values
/// collected and the next value.
///
/// - 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 (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
///
/// producer
/// .collect { values, next in next == 7 }
/// .startWithNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(1)
/// observer.sendNext(7)
/// observer.sendNext(7)
/// observer.sendNext(5)
/// observer.sendNext(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
/// (`next`) 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], _ next: Value) -> Bool) -> SignalProducer<[Value], Error> {
return lift { $0.collect(predicate) }
}
/// 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 producer that, when started, will yield `self` values on
/// provided scheduler.
public func observe(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.observe(on: scheduler) }
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return liftLeft(Signal.combineLatest)(other)
}
/// Combine the latest value of the receiver with the latest value from
/// the given signal.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either input is interrupted, the returned producer will also
/// be interrupted.
///
/// - parameters:
/// - other: A signal to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given signal.
public func combineLatest<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
return lift(Signal.combineLatest(with:))(other)
}
/// Delay `next` 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 `next` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A producer that, when started, will delay `next` and
/// `completed` events and will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
return lift { $0.delay(interval, on: scheduler) }
}
/// Skip the first `count` values, then forward everything afterward.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A producer that, when started, will skip the first `count`
/// values, then forward everything afterward.
public func skip(first count: Int) -> SignalProducer<Value, Error> {
return lift { $0.skip(first: count) }
}
/// Treats all Events from the input producer 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
/// producer will send the Event itself and then complete. When an
/// `interrupted` event is received, the resulting producer will
/// send the `Event` itself and then interrupt.
///
/// - returns: A producer that sends events as its values.
public func materialize() -> SignalProducer<Event<Value, Error>, NoError> {
return lift { $0.materialize() }
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `next` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `next` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<T>(with sampler: SignalProducer<T, NoError>) -> SignalProducer<(Value, T), Error> {
return liftLeft(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `next` 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 `next` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`
/// and `sampler`, sampled (possibly multiple times) by
/// `sampler`, then complete once both input producers have
/// completed, or interrupt if either input producer is
/// interrupted.
public func sample<T>(with sampler: Signal<T, NoError>) -> SignalProducer<(Value, T), Error> {
return lift(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `next`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `next` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample(on sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftLeft(Signal.sample(on:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `next`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - trigger: A signal whose `next` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A producer that will send values from `self`, sampled
/// (possibly multiple times) by `sampler`, then complete once
/// both inputs have completed, or interrupt if either input is
/// interrupted.
public func sample(on sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.sample(on:))(sampler)
}
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned producer will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// producer to complete.
///
/// - returns: A producer that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> {
return take(until: lifetime.ended)
}
/// Forward events from `self` until `trigger` sends a `next` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `next` or `completed` events will stop the
/// delivery of `next` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `next` or `completed` events.
public func take(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
// This should be the implementation of this method:
// return liftRight(Signal.takeUntil)(trigger)
//
// However, due to a Swift miscompilation (with `-O`) we need to inline
// `liftRight` here.
//
// See https://github.com/ReactiveCocoa/ReactiveCocoa/issues/2751 for
// more details.
//
// This can be reverted once tests with -O work correctly.
return SignalProducer { observer, outerDisposable in
self.startWithSignal { signal, disposable in
outerDisposable.add(disposable)
trigger.startWithSignal { triggerSignal, triggerDisposable in
outerDisposable += triggerDisposable
signal.take(until: triggerSignal).observe(observer)
}
}
}
}
/// Forward events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A signal whose `next` or `completed` events will stop the
/// delivery of `next` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `next` or `completed` events.
public func take(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.take(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `next`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `next` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `next` or `completed` events.
public func skip(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
return liftRight(Signal.skip(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `next`
/// or `completed`, at which point the returned signal behaves exactly like
/// `signal`.
///
/// - parameters:
/// - trigger: A signal whose `next` or `completed` events will start the
/// deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `next` or `completed` events.
public func skip(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
return lift(Signal.skip(until:))(trigger)
}
/// Forward events from `self` with history: values of the returned producer
/// are a tuple whose first member is the previous value and whose second
/// member is the current value. `initial` is supplied as the first member
/// when `self` sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A producer that sends tuples that contain previous and
/// current sent values of `self`.
public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> {
return lift { $0.combinePrevious(initial) }
}
/// Send only the final value and then immediately completes.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A producer that sends accumulated value after `self`
/// completes.
public func reduce<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.reduce(initial, combine) }
}
/// Aggregate `self`'s values into a single combined value. When `self`
/// emits its first value, `combine` is invoked with `initial` as the first
/// argument and that emitted value as the second argument. The result is
/// emitted from the producer returned from `scan`. That result is then
/// passed to `combine` as the first argument when the next value is
/// emitted, and so on.
///
/// - parameters:
/// - initial: Initial value for the accumulator.
/// - combine: A closure that accepts accumulator and sent value of
/// `self`.
///
/// - returns: A producer that sends accumulated value each time `self`
/// emits own value.
public func scan<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return lift { $0.scan(initial, combine) }
}
/// Forward only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A producer that does not send two equal values sequentially.
public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skipRepeats(isRepeat) }
}
/// Do not forward any values from `self` until `predicate` returns false,
/// at which point the returned producer behaves exactly like `self`.
///
/// - parameters:
/// - predicate: A closure that accepts a value and returns whether `self`
/// should still not forward that value to a `producer`.
///
/// - returns: A producer that sends only forwarded values from `self`.
public func skip(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return lift { $0.skip(while: predicate) }
}
/// Forward events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `next`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(untilReplacement:))(signal)
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A signal to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `next`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement signal: Signal<Value, Error>) -> SignalProducer<Value, Error> {
return lift(Signal.take(untilReplacement:))(signal)
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned producer.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A producer that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> SignalProducer<Value, Error> {
return lift { $0.take(last: count) }
}
/// Forward any values from `self` until `predicate` returns false, at which
/// point the returned producer will complete.
///
/// - parameters:
/// - predicate: A closure that accepts value and returns `Bool` value