SignalProducer.swift 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. import Dispatch
  2. import Foundation
  3. import Result
  4. /// A SignalProducer creates Signals that can produce values of type `Value`
  5. /// and/or fail with errors of type `Error`. If no failure should be possible,
  6. /// `NoError` can be specified for `Error`.
  7. ///
  8. /// SignalProducers can be used to represent operations or tasks, like network
  9. /// requests, where each invocation of `start()` will create a new underlying
  10. /// operation. This ensures that consumers will receive the results, versus a
  11. /// plain Signal, where the results might be sent before any observers are
  12. /// attached.
  13. ///
  14. /// Because of the behavior of `start()`, different Signals created from the
  15. /// producer may see a different version of Events. The Events may arrive in a
  16. /// different order between Signals, or the stream might be completely
  17. /// different!
  18. public struct SignalProducer<Value, Error: Swift.Error> {
  19. public typealias ProducedSignal = Signal<Value, Error>
  20. private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> Void
  21. /// Initializes a `SignalProducer` that will emit the same events as the
  22. /// given signal.
  23. ///
  24. /// If the Disposable returned from `start()` is disposed or a terminating
  25. /// event is sent to the observer, the given signal will be disposed.
  26. ///
  27. /// - parameters:
  28. /// - signal: A signal to observe after starting the producer.
  29. public init<S: SignalProtocol>(_ signal: S) where S.Value == Value, S.Error == Error {
  30. self.init { observer, disposable in
  31. disposable += signal.observe(observer)
  32. }
  33. }
  34. /// Initializes a SignalProducer that will invoke the given closure once for
  35. /// each invocation of `start()`.
  36. ///
  37. /// The events that the closure puts into the given observer will become
  38. /// the events sent by the started `Signal` to its observers.
  39. ///
  40. /// - note: If the `Disposable` returned from `start()` is disposed or a
  41. /// terminating event is sent to the observer, the given
  42. /// `CompositeDisposable` will be disposed, at which point work
  43. /// should be interrupted and any temporary resources cleaned up.
  44. ///
  45. /// - parameters:
  46. /// - startHandler: A closure that accepts observer and a disposable.
  47. public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void) {
  48. self.startHandler = startHandler
  49. }
  50. /// Creates a producer for a `Signal` that will immediately send one value
  51. /// then complete.
  52. ///
  53. /// - parameters:
  54. /// - value: A value that should be sent by the `Signal` in a `value`
  55. /// event.
  56. public init(value: Value) {
  57. self.init { observer, disposable in
  58. observer.send(value: value)
  59. observer.sendCompleted()
  60. }
  61. }
  62. /// Creates a producer for a `Signal` that will immediately fail with the
  63. /// given error.
  64. ///
  65. /// - parameters:
  66. /// - error: An error that should be sent by the `Signal` in a `failed`
  67. /// event.
  68. public init(error: Error) {
  69. self.init { observer, disposable in
  70. observer.send(error: error)
  71. }
  72. }
  73. /// Creates a producer for a Signal that will immediately send one value
  74. /// then complete, or immediately fail, depending on the given Result.
  75. ///
  76. /// - parameters:
  77. /// - result: A `Result` instance that will send either `value` event if
  78. /// `result` is `success`ful or `failed` event if `result` is a
  79. /// `failure`.
  80. public init(result: Result<Value, Error>) {
  81. switch result {
  82. case let .success(value):
  83. self.init(value: value)
  84. case let .failure(error):
  85. self.init(error: error)
  86. }
  87. }
  88. /// Creates a producer for a Signal that will immediately send the values
  89. /// from the given sequence, then complete.
  90. ///
  91. /// - parameters:
  92. /// - values: A sequence of values that a `Signal` will send as separate
  93. /// `value` events and then complete.
  94. public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
  95. self.init { observer, disposable in
  96. for value in values {
  97. observer.send(value: value)
  98. if disposable.isDisposed {
  99. break
  100. }
  101. }
  102. observer.sendCompleted()
  103. }
  104. }
  105. /// Creates a producer for a Signal that will immediately send the values
  106. /// from the given sequence, then complete.
  107. ///
  108. /// - parameters:
  109. /// - first: First value for the `Signal` to send.
  110. /// - second: Second value for the `Signal` to send.
  111. /// - tail: Rest of the values to be sent by the `Signal`.
  112. public init(values first: Value, _ second: Value, _ tail: Value...) {
  113. self.init([ first, second ] + tail)
  114. }
  115. /// A producer for a Signal that will immediately complete without sending
  116. /// any values.
  117. public static var empty: SignalProducer {
  118. return self.init { observer, disposable in
  119. observer.sendCompleted()
  120. }
  121. }
  122. /// A producer for a Signal that never sends any events to its observers.
  123. public static var never: SignalProducer {
  124. return self.init { _ in return }
  125. }
  126. /// Create a Signal from the producer, pass it into the given closure,
  127. /// then start sending events on the Signal when the closure has returned.
  128. ///
  129. /// The closure will also receive a disposable which can be used to
  130. /// interrupt the work associated with the signal and immediately send an
  131. /// `interrupted` event.
  132. ///
  133. /// - parameters:
  134. /// - setUp: A closure that accepts a `signal` and `interrupter`.
  135. public func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void) {
  136. // Disposes of the work associated with the SignalProducer and any
  137. // upstream producers.
  138. let producerDisposable = CompositeDisposable()
  139. let (signal, observer) = Signal<Value, Error>.pipe(disposable: producerDisposable)
  140. // Directly disposed of when `start()` or `startWithSignal()` is
  141. // disposed.
  142. let cancelDisposable = ActionDisposable(action: observer.sendInterrupted)
  143. setup(signal, cancelDisposable)
  144. if cancelDisposable.isDisposed {
  145. return
  146. }
  147. startHandler(observer, producerDisposable)
  148. }
  149. }
  150. /// A protocol used to constraint `SignalProducer` operators.
  151. public protocol SignalProducerProtocol {
  152. /// The type of values being sent on the producer
  153. associatedtype Value
  154. /// The type of error that can occur on the producer. If errors aren't possible
  155. /// then `NoError` can be used.
  156. associatedtype Error: Swift.Error
  157. /// Extracts a signal producer from the receiver.
  158. var producer: SignalProducer<Value, Error> { get }
  159. /// Initialize a signal
  160. init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void)
  161. /// Creates a Signal from the producer, passes it into the given closure,
  162. /// then starts sending events on the Signal when the closure has returned.
  163. func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void)
  164. }
  165. extension SignalProducer: SignalProducerProtocol {
  166. public var producer: SignalProducer {
  167. return self
  168. }
  169. }
  170. extension SignalProducerProtocol {
  171. /// Create a Signal from the producer, then attach the given observer to
  172. /// the `Signal` as an observer.
  173. ///
  174. /// - parameters:
  175. /// - observer: An observer to attach to produced signal.
  176. ///
  177. /// - returns: A `Disposable` which can be used to interrupt the work
  178. /// associated with the signal and immediately send an
  179. /// `interrupted` event.
  180. @discardableResult
  181. public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
  182. var disposable: Disposable!
  183. startWithSignal { signal, innerDisposable in
  184. signal.observe(observer)
  185. disposable = innerDisposable
  186. }
  187. return disposable
  188. }
  189. /// Convenience override for start(_:) to allow trailing-closure style
  190. /// invocations.
  191. ///
  192. /// - parameters:
  193. /// - observerAction: A closure that accepts `Event` sent by the produced
  194. /// signal.
  195. ///
  196. /// - returns: A `Disposable` which can be used to interrupt the work
  197. /// associated with the signal and immediately send an
  198. /// `interrupted` event.
  199. @discardableResult
  200. public func start(_ observerAction: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
  201. return start(Observer(observerAction))
  202. }
  203. /// Create a Signal from the producer, then add an observer to the `Signal`,
  204. /// which will invoke the given callback when `value` or `failed` events are
  205. /// received.
  206. ///
  207. /// - parameters:
  208. /// - result: A closure that accepts a `result` that contains a `.success`
  209. /// case for `value` events or `.failure` case for `failed` event.
  210. ///
  211. /// - returns: A Disposable which can be used to interrupt the work
  212. /// associated with the Signal, and prevent any future callbacks
  213. /// from being invoked.
  214. @discardableResult
  215. public func startWithResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable {
  216. return start(
  217. Observer(
  218. value: { result(.success($0)) },
  219. failed: { result(.failure($0)) }
  220. )
  221. )
  222. }
  223. /// Create a Signal from the producer, then add exactly one observer to the
  224. /// Signal, which will invoke the given callback when a `completed` event is
  225. /// received.
  226. ///
  227. /// - parameters:
  228. /// - completed: A closure that will be envoked when produced signal sends
  229. /// `completed` event.
  230. ///
  231. /// - returns: A `Disposable` which can be used to interrupt the work
  232. /// associated with the signal.
  233. @discardableResult
  234. public func startWithCompleted(_ completed: @escaping () -> Void) -> Disposable {
  235. return start(Observer(completed: completed))
  236. }
  237. /// Creates a Signal from the producer, then adds exactly one observer to
  238. /// the Signal, which will invoke the given callback when a `failed` event
  239. /// is received.
  240. ///
  241. /// - parameters:
  242. /// - failed: A closure that accepts an error object.
  243. ///
  244. /// - returns: A `Disposable` which can be used to interrupt the work
  245. /// associated with the signal.
  246. @discardableResult
  247. public func startWithFailed(_ failed: @escaping (Error) -> Void) -> Disposable {
  248. return start(Observer(failed: failed))
  249. }
  250. /// Creates a Signal from the producer, then adds exactly one observer to
  251. /// the Signal, which will invoke the given callback when an `interrupted`
  252. /// event is received.
  253. ///
  254. /// - parameters:
  255. /// - interrupted: A closure that is invoked when `interrupted` event is
  256. /// received.
  257. ///
  258. /// - returns: A `Disposable` which can be used to interrupt the work
  259. /// associated with the signal.
  260. @discardableResult
  261. public func startWithInterrupted(_ interrupted: @escaping () -> Void) -> Disposable {
  262. return start(Observer(interrupted: interrupted))
  263. }
  264. /// Creates a `Signal` from the producer.
  265. ///
  266. /// This is equivalent to `SignalProducer.startWithSignal`, but it has
  267. /// the downside that any values emitted synchronously upon starting will
  268. /// be missed by the observer, because it won't be able to subscribe in time.
  269. /// That's why we don't want this method to be exposed as `public`,
  270. /// but it's useful internally.
  271. internal func startAndRetrieveSignal() -> Signal<Value, Error> {
  272. var result: Signal<Value, Error>!
  273. self.startWithSignal { signal, _ in
  274. result = signal
  275. }
  276. return result
  277. }
  278. }
  279. extension SignalProducerProtocol where Error == NoError {
  280. /// Create a Signal from the producer, then add exactly one observer to
  281. /// the Signal, which will invoke the given callback when `value` events are
  282. /// received.
  283. ///
  284. /// - parameters:
  285. /// - value: A closure that accepts a value carried by `value` event.
  286. ///
  287. /// - returns: A `Disposable` which can be used to interrupt the work
  288. /// associated with the Signal, and prevent any future callbacks
  289. /// from being invoked.
  290. @discardableResult
  291. public func startWithValues(_ value: @escaping (Value) -> Void) -> Disposable {
  292. return start(Observer(value: value))
  293. }
  294. }
  295. extension SignalProducerProtocol {
  296. /// Lift an unary Signal operator to operate upon SignalProducers instead.
  297. ///
  298. /// In other words, this will create a new `SignalProducer` which will apply
  299. /// the given `Signal` operator to _every_ created `Signal`, just as if the
  300. /// operator had been applied to each `Signal` yielded from `start()`.
  301. ///
  302. /// - parameters:
  303. /// - transform: An unary operator to lift.
  304. ///
  305. /// - returns: A signal producer that applies signal's operator to every
  306. /// created signal.
  307. public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> {
  308. return SignalProducer { observer, outerDisposable in
  309. self.startWithSignal { signal, innerDisposable in
  310. outerDisposable += innerDisposable
  311. transform(signal).observe(observer)
  312. }
  313. }
  314. }
  315. /// Lift a binary Signal operator to operate upon SignalProducers instead.
  316. ///
  317. /// In other words, this will create a new `SignalProducer` which will apply
  318. /// the given `Signal` operator to _every_ `Signal` created from the two
  319. /// producers, just as if the operator had been applied to each `Signal`
  320. /// yielded from `start()`.
  321. ///
  322. /// - note: starting the returned producer will start the receiver of the
  323. /// operator, which may not be adviseable for some operators.
  324. ///
  325. /// - parameters:
  326. /// - transform: A binary operator to lift.
  327. ///
  328. /// - returns: A binary operator that operates on two signal producers.
  329. public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
  330. return liftRight(transform)
  331. }
  332. /// Right-associative lifting of a binary signal operator over producers.
  333. /// That is, the argument producer will be started before the receiver. When
  334. /// both producers are synchronous this order can be important depending on
  335. /// the operator to generate correct results.
  336. private func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
  337. return { otherProducer in
  338. return SignalProducer { observer, outerDisposable in
  339. self.startWithSignal { signal, disposable in
  340. outerDisposable.add(disposable)
  341. otherProducer.startWithSignal { otherSignal, otherDisposable in
  342. outerDisposable += otherDisposable
  343. transform(signal)(otherSignal).observe(observer)
  344. }
  345. }
  346. }
  347. }
  348. }
  349. /// Left-associative lifting of a binary signal operator over producers.
  350. /// That is, the receiver will be started before the argument producer. When
  351. /// both producers are synchronous this order can be important depending on
  352. /// the operator to generate correct results.
  353. private func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
  354. return { otherProducer in
  355. return SignalProducer { observer, outerDisposable in
  356. otherProducer.startWithSignal { otherSignal, otherDisposable in
  357. outerDisposable += otherDisposable
  358. self.startWithSignal { signal, disposable in
  359. outerDisposable.add(disposable)
  360. transform(signal)(otherSignal).observe(observer)
  361. }
  362. }
  363. }
  364. }
  365. }
  366. /// Lift a binary Signal operator to operate upon a Signal and a
  367. /// SignalProducer instead.
  368. ///
  369. /// In other words, this will create a new `SignalProducer` which will apply
  370. /// the given `Signal` operator to _every_ `Signal` created from the two
  371. /// producers, just as if the operator had been applied to each `Signal`
  372. /// yielded from `start()`.
  373. ///
  374. /// - parameters:
  375. /// - transform: A binary operator to lift.
  376. ///
  377. /// - returns: A binary operator that works on `Signal` and returns
  378. /// `SignalProducer`.
  379. public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (Signal<U, F>) -> SignalProducer<V, G> {
  380. return { otherSignal in
  381. return self.liftRight(transform)(SignalProducer(otherSignal))
  382. }
  383. }
  384. /// Map each value in the producer to a new value.
  385. ///
  386. /// - parameters:
  387. /// - transform: A closure that accepts a value and returns a different
  388. /// value.
  389. ///
  390. /// - returns: A signal producer that, when started, will send a mapped
  391. /// value of `self.`
  392. public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
  393. return lift { $0.map(transform) }
  394. }
  395. /// Map errors in the producer to a new error.
  396. ///
  397. /// - parameters:
  398. /// - transform: A closure that accepts an error object and returns a
  399. /// different error.
  400. ///
  401. /// - returns: A producer that emits errors of new type.
  402. public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> {
  403. return lift { $0.mapError(transform) }
  404. }
  405. /// Preserve only the values of the producer that pass the given predicate.
  406. ///
  407. /// - parameters:
  408. /// - predicate: A closure that accepts value and returns `Bool` denoting
  409. /// whether value has passed the test.
  410. ///
  411. /// - returns: A producer that, when started, will send only the values
  412. /// passing the given predicate.
  413. public func filter(_ predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
  414. return lift { $0.filter(predicate) }
  415. }
  416. /// Yield the first `count` values from the input producer.
  417. ///
  418. /// - precondition: `count` must be non-negative number.
  419. ///
  420. /// - parameters:
  421. /// - count: A number of values to take from the signal.
  422. ///
  423. /// - returns: A producer that, when started, will yield the first `count`
  424. /// values from `self`.
  425. public func take(first count: Int) -> SignalProducer<Value, Error> {
  426. return lift { $0.take(first: count) }
  427. }
  428. /// Yield an array of values when `self` completes.
  429. ///
  430. /// - note: When `self` completes without collecting any value, it will send
  431. /// an empty array of values.
  432. ///
  433. /// - returns: A producer that, when started, will yield an array of values
  434. /// when `self` completes.
  435. public func collect() -> SignalProducer<[Value], Error> {
  436. return lift { $0.collect() }
  437. }
  438. /// Yield an array of values until it reaches a certain count.
  439. ///
  440. /// - precondition: `count` should be greater than zero.
  441. ///
  442. /// - note: When the count is reached the array is sent and the signal
  443. /// starts over yielding a new array of values.
  444. ///
  445. /// - note: When `self` completes any remaining values will be sent, the
  446. /// last array may not have `count` values. Alternatively, if were
  447. /// not collected any values will sent an empty array of values.
  448. ///
  449. /// - returns: A producer that, when started, collects at most `count`
  450. /// values from `self`, forwards them as a single array and
  451. /// completes.
  452. public func collect(count: Int) -> SignalProducer<[Value], Error> {
  453. precondition(count > 0)
  454. return lift { $0.collect(count: count) }
  455. }
  456. /// Yield an array of values based on a predicate which matches the values
  457. /// collected.
  458. ///
  459. /// - note: When `self` completes any remaining values will be sent, the
  460. /// last array may not match `predicate`. Alternatively, if were not
  461. /// collected any values will sent an empty array of values.
  462. ///
  463. /// ````
  464. /// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
  465. ///
  466. /// producer
  467. /// .collect { values in values.reduce(0, combine: +) == 8 }
  468. /// .startWithValues { print($0) }
  469. ///
  470. /// observer.send(value: 1)
  471. /// observer.send(value: 3)
  472. /// observer.send(value: 4)
  473. /// observer.send(value: 7)
  474. /// observer.send(value: 1)
  475. /// observer.send(value: 5)
  476. /// observer.send(value: 6)
  477. /// observer.sendCompleted()
  478. ///
  479. /// // Output:
  480. /// // [1, 3, 4]
  481. /// // [7, 1]
  482. /// // [5, 6]
  483. /// ````
  484. ///
  485. /// - parameters:
  486. /// - predicate: Predicate to match when values should be sent (returning
  487. /// `true`) or alternatively when they should be collected
  488. /// (where it should return `false`). The most recent value
  489. /// (`value`) is included in `values` and will be the end of
  490. /// the current array of values if the predicate returns
  491. /// `true`.
  492. ///
  493. /// - returns: A producer that, when started, collects values passing the
  494. /// predicate and, when `self` completes, forwards them as a
  495. /// single array and complets.
  496. public func collect(_ predicate: @escaping (_ values: [Value]) -> Bool) -> SignalProducer<[Value], Error> {
  497. return lift { $0.collect(predicate) }
  498. }
  499. /// Yield an array of values based on a predicate which matches the values
  500. /// collected and the next value.
  501. ///
  502. /// - note: When `self` completes any remaining values will be sent, the
  503. /// last array may not match `predicate`. Alternatively, if no
  504. /// values were collected an empty array will be sent.
  505. ///
  506. /// ````
  507. /// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1)
  508. ///
  509. /// producer
  510. /// .collect { values, value in value == 7 }
  511. /// .startWithValues { print($0) }
  512. ///
  513. /// observer.send(value: 1)
  514. /// observer.send(value: 1)
  515. /// observer.send(value: 7)
  516. /// observer.send(value: 7)
  517. /// observer.send(value: 5)
  518. /// observer.send(value: 6)
  519. /// observer.sendCompleted()
  520. ///
  521. /// // Output:
  522. /// // [1, 1]
  523. /// // [7]
  524. /// // [7, 5, 6]
  525. /// ````
  526. ///
  527. /// - parameters:
  528. /// - predicate: Predicate to match when values should be sent (returning
  529. /// `true`) or alternatively when they should be collected
  530. /// (where it should return `false`). The most recent value
  531. /// (`vaule`) is not included in `values` and will be the
  532. /// start of the next array of values if the predicate
  533. /// returns `true`.
  534. ///
  535. /// - returns: A signal that will yield an array of values based on a
  536. /// predicate which matches the values collected and the next
  537. /// value.
  538. public func collect(_ predicate: @escaping (_ values: [Value], _ value: Value) -> Bool) -> SignalProducer<[Value], Error> {
  539. return lift { $0.collect(predicate) }
  540. }
  541. /// Forward all events onto the given scheduler, instead of whichever
  542. /// scheduler they originally arrived upon.
  543. ///
  544. /// - parameters:
  545. /// - scheduler: A scheduler to deliver events on.
  546. ///
  547. /// - returns: A producer that, when started, will yield `self` values on
  548. /// provided scheduler.
  549. public func observe(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> {
  550. return lift { $0.observe(on: scheduler) }
  551. }
  552. /// Combine the latest value of the receiver with the latest value from the
  553. /// given producer.
  554. ///
  555. /// - note: The returned producer will not send a value until both inputs
  556. /// have sent at least one value each.
  557. ///
  558. /// - note: If either producer is interrupted, the returned producer will
  559. /// also be interrupted.
  560. ///
  561. /// - parameters:
  562. /// - other: A producer to combine `self`'s value with.
  563. ///
  564. /// - returns: A producer that, when started, will yield a tuple containing
  565. /// values of `self` and given producer.
  566. public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
  567. return liftLeft(Signal.combineLatest)(other)
  568. }
  569. /// Combine the latest value of the receiver with the latest value from
  570. /// the given signal.
  571. ///
  572. /// - note: The returned producer will not send a value until both inputs
  573. /// have sent at least one value each.
  574. ///
  575. /// - note: If either input is interrupted, the returned producer will also
  576. /// be interrupted.
  577. ///
  578. /// - parameters:
  579. /// - other: A signal to combine `self`'s value with.
  580. ///
  581. /// - returns: A producer that, when started, will yield a tuple containing
  582. /// values of `self` and given signal.
  583. public func combineLatest<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
  584. return lift(Signal.combineLatest(with:))(other)
  585. }
  586. /// Delay `value` and `completed` events by the given interval, forwarding
  587. /// them on the given scheduler.
  588. ///
  589. /// - note: `failed` and `interrupted` events are always scheduled
  590. /// immediately.
  591. ///
  592. /// - parameters:
  593. /// - interval: Interval to delay `value` and `completed` events by.
  594. /// - scheduler: A scheduler to deliver delayed events on.
  595. ///
  596. /// - returns: A producer that, when started, will delay `value` and
  597. /// `completed` events and will yield them on given scheduler.
  598. public func delay(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
  599. return lift { $0.delay(interval, on: scheduler) }
  600. }
  601. /// Skip the first `count` values, then forward everything afterward.
  602. ///
  603. /// - parameters:
  604. /// - count: A number of values to skip.
  605. ///
  606. /// - returns: A producer that, when started, will skip the first `count`
  607. /// values, then forward everything afterward.
  608. public func skip(first count: Int) -> SignalProducer<Value, Error> {
  609. return lift { $0.skip(first: count) }
  610. }
  611. /// Treats all Events from the input producer as plain values, allowing them
  612. /// to be manipulated just like any other value.
  613. ///
  614. /// In other words, this brings Events “into the monad.”
  615. ///
  616. /// - note: When a Completed or Failed event is received, the resulting
  617. /// producer will send the Event itself and then complete. When an
  618. /// `interrupted` event is received, the resulting producer will
  619. /// send the `Event` itself and then interrupt.
  620. ///
  621. /// - returns: A producer that sends events as its values.
  622. public func materialize() -> SignalProducer<Event<Value, Error>, NoError> {
  623. return lift { $0.materialize() }
  624. }
  625. /// Forward the latest value from `self` with the value from `sampler` as a
  626. /// tuple, only when `sampler` sends a `value` event.
  627. ///
  628. /// - note: If `sampler` fires before a value has been observed on `self`,
  629. /// nothing happens.
  630. ///
  631. /// - parameters:
  632. /// - sampler: A producer that will trigger the delivery of `value` event
  633. /// from `self`.
  634. ///
  635. /// - returns: A producer that will send values from `self` and `sampler`,
  636. /// sampled (possibly multiple times) by `sampler`, then complete
  637. /// once both input producers have completed, or interrupt if
  638. /// either input producer is interrupted.
  639. public func sample<T>(with sampler: SignalProducer<T, NoError>) -> SignalProducer<(Value, T), Error> {
  640. return liftLeft(Signal.sample(with:))(sampler)
  641. }
  642. /// Forward the latest value from `self` with the value from `sampler` as a
  643. /// tuple, only when `sampler` sends a `value` event.
  644. ///
  645. /// - note: If `sampler` fires before a value has been observed on `self`,
  646. /// nothing happens.
  647. ///
  648. /// - parameters:
  649. /// - sampler: A signal that will trigger the delivery of `value` event
  650. /// from `self`.
  651. ///
  652. /// - returns: A producer that, when started, will send values from `self`
  653. /// and `sampler`, sampled (possibly multiple times) by
  654. /// `sampler`, then complete once both input producers have
  655. /// completed, or interrupt if either input producer is
  656. /// interrupted.
  657. public func sample<T>(with sampler: Signal<T, NoError>) -> SignalProducer<(Value, T), Error> {
  658. return lift(Signal.sample(with:))(sampler)
  659. }
  660. /// Forward the latest value from `self` whenever `sampler` sends a `value`
  661. /// event.
  662. ///
  663. /// - note: If `sampler` fires before a value has been observed on `self`,
  664. /// nothing happens.
  665. ///
  666. /// - parameters:
  667. /// - sampler: A producer that will trigger the delivery of `value` event
  668. /// from `self`.
  669. ///
  670. /// - returns: A producer that, when started, will send values from `self`,
  671. /// sampled (possibly multiple times) by `sampler`, then complete
  672. /// once both input producers have completed, or interrupt if
  673. /// either input producer is interrupted.
  674. public func sample(on sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
  675. return liftLeft(Signal.sample(on:))(sampler)
  676. }
  677. /// Forward the latest value from `self` whenever `sampler` sends a `value`
  678. /// event.
  679. ///
  680. /// - note: If `sampler` fires before a value has been observed on `self`,
  681. /// nothing happens.
  682. ///
  683. /// - parameters:
  684. /// - trigger: A signal whose `value` or `completed` events will start the
  685. /// deliver of events on `self`.
  686. ///
  687. /// - returns: A producer that will send values from `self`, sampled
  688. /// (possibly multiple times) by `sampler`, then complete once
  689. /// both inputs have completed, or interrupt if either input is
  690. /// interrupted.
  691. public func sample(on sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> {
  692. return lift(Signal.sample(on:))(sampler)
  693. }
  694. /// Forward the latest value from `samplee` with the value from `self` as a
  695. /// tuple, only when `self` sends a `value` event.
  696. /// This is like a flipped version of `sample(with:)`, but `samplee`'s
  697. /// terminal events are completely ignored.
  698. ///
  699. /// - note: If `self` fires before a value has been observed on `samplee`,
  700. /// nothing happens.
  701. ///
  702. /// - parameters:
  703. /// - samplee: A producer whose latest value is sampled by `self`.
  704. ///
  705. /// - returns: A signal that will send values from `self` and `samplee`,
  706. /// sampled (possibly multiple times) by `self`, then terminate
  707. /// once `self` has terminated. **`samplee`'s terminated events
  708. /// are ignored**.
  709. public func withLatest<U>(from samplee: SignalProducer<U, NoError>) -> SignalProducer<(Value, U), Error> {
  710. return liftRight(Signal.withLatest)(samplee)
  711. }
  712. /// Forward the latest value from `samplee` with the value from `self` as a
  713. /// tuple, only when `self` sends a `value` event.
  714. /// This is like a flipped version of `sample(with:)`, but `samplee`'s
  715. /// terminal events are completely ignored.
  716. ///
  717. /// - note: If `self` fires before a value has been observed on `samplee`,
  718. /// nothing happens.
  719. ///
  720. /// - parameters:
  721. /// - samplee: A signal whose latest value is sampled by `self`.
  722. ///
  723. /// - returns: A signal that will send values from `self` and `samplee`,
  724. /// sampled (possibly multiple times) by `self`, then terminate
  725. /// once `self` has terminated. **`samplee`'s terminated events
  726. /// are ignored**.
  727. public func withLatest<U>(from samplee: Signal<U, NoError>) -> SignalProducer<(Value, U), Error> {
  728. return lift(Signal.withLatest)(samplee)
  729. }
  730. /// Forwards events from `self` until `lifetime` ends, at which point the
  731. /// returned producer will complete.
  732. ///
  733. /// - parameters:
  734. /// - lifetime: A lifetime whose `ended` signal will cause the returned
  735. /// producer to complete.
  736. ///
  737. /// - returns: A producer that will deliver events until `lifetime` ends.
  738. public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> {
  739. return take(until: lifetime.ended)
  740. }
  741. /// Forward events from `self` until `trigger` sends a `value` or `completed`
  742. /// event, at which point the returned producer will complete.
  743. ///
  744. /// - parameters:
  745. /// - trigger: A producer whose `value` or `completed` events will stop the
  746. /// delivery of `value` events from `self`.
  747. ///
  748. /// - returns: A producer that will deliver events until `trigger` sends
  749. /// `value` or `completed` events.
  750. public func take(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
  751. return liftRight(Signal.take(until:))(trigger)
  752. }
  753. /// Forward events from `self` until `trigger` sends a `value` or
  754. /// `completed` event, at which point the returned producer will complete.
  755. ///
  756. /// - parameters:
  757. /// - trigger: A signal whose `value` or `completed` events will stop the
  758. /// delivery of `value` events from `self`.
  759. ///
  760. /// - returns: A producer that will deliver events until `trigger` sends
  761. /// `value` or `completed` events.
  762. public func take(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
  763. return lift(Signal.take(until:))(trigger)
  764. }
  765. /// Do not forward any values from `self` until `trigger` sends a `value`
  766. /// or `completed`, at which point the returned producer behaves exactly
  767. /// like `producer`.
  768. ///
  769. /// - parameters:
  770. /// - trigger: A producer whose `value` or `completed` events will start
  771. /// the deliver of events on `self`.
  772. ///
  773. /// - returns: A producer that will deliver events once the `trigger` sends
  774. /// `value` or `completed` events.
  775. public func skip(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> {
  776. return liftRight(Signal.skip(until:))(trigger)
  777. }
  778. /// Do not forward any values from `self` until `trigger` sends a `value`
  779. /// or `completed`, at which point the returned signal behaves exactly like
  780. /// `signal`.
  781. ///
  782. /// - parameters:
  783. /// - trigger: A signal whose `value` or `completed` events will start the
  784. /// deliver of events on `self`.
  785. ///
  786. /// - returns: A producer that will deliver events once the `trigger` sends
  787. /// `value` or `completed` events.
  788. public func skip(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> {
  789. return lift(Signal.skip(until:))(trigger)
  790. }
  791. /// Forward events from `self` with history: values of the returned producer
  792. /// are a tuple whose first member is the previous value and whose second
  793. /// member is the current value. `initial` is supplied as the first member
  794. /// when `self` sends its first value.
  795. ///
  796. /// - parameters:
  797. /// - initial: A value that will be combined with the first value sent by
  798. /// `self`.
  799. ///
  800. /// - returns: A producer that sends tuples that contain previous and
  801. /// current sent values of `self`.
  802. public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> {
  803. return lift { $0.combinePrevious(initial) }
  804. }
  805. /// Send only the final value and then immediately completes.
  806. ///
  807. /// - parameters:
  808. /// - initial: Initial value for the accumulator.
  809. /// - combine: A closure that accepts accumulator and sent value of
  810. /// `self`.
  811. ///
  812. /// - returns: A producer that sends accumulated value after `self`
  813. /// completes.
  814. public func reduce<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
  815. return lift { $0.reduce(initial, combine) }
  816. }
  817. /// Aggregate `self`'s values into a single combined value. When `self`
  818. /// emits its first value, `combine` is invoked with `initial` as the first
  819. /// argument and that emitted value as the second argument. The result is
  820. /// emitted from the producer returned from `scan`. That result is then
  821. /// passed to `combine` as the first argument when the next value is
  822. /// emitted, and so on.
  823. ///
  824. /// - parameters:
  825. /// - initial: Initial value for the accumulator.
  826. /// - combine: A closure that accepts accumulator and sent value of
  827. /// `self`.
  828. ///
  829. /// - returns: A producer that sends accumulated value each time `self`
  830. /// emits own value.
  831. public func scan<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
  832. return lift { $0.scan(initial, combine) }
  833. }
  834. /// Forward only those values from `self` which do not pass `isRepeat` with
  835. /// respect to the previous value.
  836. ///
  837. /// - note: The first value is always forwarded.
  838. ///
  839. /// - returns: A producer that does not send two equal values sequentially.
  840. public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
  841. return lift { $0.skipRepeats(isRepeat) }
  842. }
  843. /// Do not forward any values from `self` until `predicate` returns false,
  844. /// at which point the returned producer behaves exactly like `self`.
  845. ///
  846. /// - parameters:
  847. /// - predicate: A closure that accepts a value and returns whether `self`
  848. /// should still not forward that value to a `producer`.
  849. ///
  850. /// - returns: A producer that sends only forwarded values from `self`.
  851. public func skip(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
  852. return lift { $0.skip(while: predicate) }
  853. }
  854. /// Forward events from `self` until `replacement` begins sending events.
  855. ///
  856. /// - parameters:
  857. /// - replacement: A producer to wait to wait for values from and start
  858. /// sending them as a replacement to `self`'s values.
  859. ///
  860. /// - returns: A producer which passes through `value`, `failed`, and
  861. /// `interrupted` events from `self` until `replacement` sends an
  862. /// event, at which point the returned producer will send that
  863. /// event and switch to passing through events from `replacement`
  864. /// instead, regardless of whether `self` has sent events
  865. /// already.
  866. public func take(untilReplacement signal: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
  867. return liftRight(Signal.take(untilReplacement:))(signal)
  868. }
  869. /// Forwards events from `self` until `replacement` begins sending events.
  870. ///
  871. /// - parameters:
  872. /// - replacement: A signal to wait to wait for values from and start
  873. /// sending them as a replacement to `self`'s values.
  874. ///
  875. /// - returns: A producer which passes through `value`, `failed`, and
  876. /// `interrupted` events from `self` until `replacement` sends an
  877. /// event, at which point the returned producer will send that
  878. /// event and switch to passing through events from `replacement`
  879. /// instead, regardless of whether `self` has sent events
  880. /// already.
  881. public func take(untilReplacement signal: Signal<Value, Error>) -> SignalProducer<Value, Error> {
  882. return lift(Signal.take(untilReplacement:))(signal)
  883. }
  884. /// Wait until `self` completes and then forward the final `count` values
  885. /// on the returned producer.
  886. ///
  887. /// - parameters:
  888. /// - count: Number of last events to send after `self` completes.
  889. ///
  890. /// - returns: A producer that receives up to `count` values from `self`
  891. /// after `self` completes.
  892. public func take(last count: Int) -> SignalProducer<Value, Error> {
  893. return lift { $0.take(last: count) }
  894. }
  895. /// Forward any values from `self` until `predicate` returns false, at which
  896. /// point the returned producer will complete.
  897. ///
  898. /// - parameters:
  899. /// - predicate: A closure that accepts value and returns `Bool` value
  900. /// whether `self` should forward it to `signal` and continue
  901. /// sending other events.
  902. ///
  903. /// - returns: A producer that sends events until the values sent by `self`
  904. /// pass the given `predicate`.
  905. public func take(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
  906. return lift { $0.take(while: predicate) }
  907. }
  908. /// Zip elements of two producers into pairs. The elements of any Nth pair
  909. /// are the Nth elements of the two input producers.
  910. ///
  911. /// - parameters:
  912. /// - other: A producer to zip values with.
  913. ///
  914. /// - returns: A producer that sends tuples of `self` and `otherProducer`.
  915. public func zip<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
  916. return liftLeft(Signal.zip(with:))(other)
  917. }
  918. /// Zip elements of this producer and a signal into pairs. The elements of
  919. /// any Nth pair are the Nth elements of the two.
  920. ///
  921. /// - parameters:
  922. /// - other: A signal to zip values with.
  923. ///
  924. /// - returns: A producer that sends tuples of `self` and `otherSignal`.
  925. public func zip<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> {
  926. return lift(Signal.zip(with:))(other)
  927. }
  928. /// Apply `operation` to values from `self` with `success`ful results
  929. /// forwarded on the returned producer and `failure`s sent as `failed`
  930. /// events.
  931. ///
  932. /// - parameters:
  933. /// - operation: A closure that accepts a value and returns a `Result`.
  934. ///
  935. /// - returns: A producer that receives `success`ful `Result` as `value`
  936. /// event and `failure` as `failed` event.
  937. public func attempt(operation: @escaping (Value) -> Result<(), Error>) -> SignalProducer<Value, Error> {
  938. return lift { $0.attempt(operation) }
  939. }
  940. /// Apply `operation` to values from `self` with `success`ful results
  941. /// mapped on the returned producer and `failure`s sent as `failed` events.
  942. ///
  943. /// - parameters:
  944. /// - operation: A closure that accepts a value and returns a result of
  945. /// a mapped value as `success`.
  946. ///
  947. /// - returns: A producer that sends mapped values from `self` if returned
  948. /// `Result` is `success`ful, `failed` events otherwise.
  949. public func attemptMap<U>(_ operation: @escaping (Value) -> Result<U, Error>) -> SignalProducer<U, Error> {
  950. return lift { $0.attemptMap(operation) }
  951. }
  952. /// Throttle values sent by the receiver, so that at least `interval`
  953. /// seconds pass between each, then forwards them on the given scheduler.
  954. ///
  955. /// - note: If multiple values are received before the interval has elapsed,
  956. /// the latest value is the one that will be passed on.
  957. ///
  958. /// - norw: If `self` terminates while a value is being throttled, that
  959. /// value will be discarded and the returned producer will terminate
  960. /// immediately.
  961. ///
  962. /// - parameters:
  963. /// - interval: Number of seconds to wait between sent values.
  964. /// - scheduler: A scheduler to deliver events on.
  965. ///
  966. /// - returns: A producer that sends values at least `interval` seconds
  967. /// appart on a given scheduler.
  968. public func throttle(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
  969. return lift { $0.throttle(interval, on: scheduler) }
  970. }
  971. /// Conditionally throttles values sent on the receiver whenever
  972. /// `shouldThrottle` is true, forwarding values on the given scheduler.
  973. ///
  974. /// - note: While `shouldThrottle` remains false, values are forwarded on the
  975. /// given scheduler. If multiple values are received while
  976. /// `shouldThrottle` is true, the latest value is the one that will
  977. /// be passed on.
  978. ///
  979. /// - note: If the input signal terminates while a value is being throttled,
  980. /// that value will be discarded and the returned signal will
  981. /// terminate immediately.
  982. ///
  983. /// - note: If `shouldThrottle` completes before the receiver, and its last
  984. /// value is `true`, the returned signal will remain in the throttled
  985. /// state, emitting no further values until it terminates.
  986. ///
  987. /// - parameters:
  988. /// - shouldThrottle: A boolean property that controls whether values
  989. /// should be throttled.
  990. /// - scheduler: A scheduler to deliver events on.
  991. ///
  992. /// - returns: A producer that sends values only while `shouldThrottle` is false.
  993. public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error>
  994. where P.Value == Bool
  995. {
  996. // Using `Property.init(_:)` avoids capturing a strong reference
  997. // to `shouldThrottle`, so that we don't extend its lifetime.
  998. let shouldThrottle = Property(shouldThrottle)
  999. return lift { $0.throttle(while: shouldThrottle, on: scheduler) }
  1000. }
  1001. /// Debounce values sent by the receiver, such that at least `interval`
  1002. /// seconds pass after the receiver has last sent a value, then
  1003. /// forward the latest value on the given scheduler.
  1004. ///
  1005. /// - note: If multiple values are received before the interval has elapsed,
  1006. /// the latest value is the one that will be passed on.
  1007. ///
  1008. /// - note: If `self` terminates while a value is being debounced,
  1009. /// that value will be discarded and the returned producer will
  1010. /// terminate immediately.
  1011. ///
  1012. /// - parameters:
  1013. /// - interval: A number of seconds to wait before sending a value.
  1014. /// - scheduler: A scheduler to send values on.
  1015. ///
  1016. /// - returns: A producer that sends values that are sent from `self` at
  1017. /// least `interval` seconds apart.
  1018. public func debounce(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
  1019. return lift { $0.debounce(interval, on: scheduler) }
  1020. }
  1021. /// Forward events from `self` until `interval`. Then if producer isn't
  1022. /// completed yet, fails with `error` on `scheduler`.
  1023. ///
  1024. /// - note: If the interval is 0, the timeout will be scheduled immediately.
  1025. /// The producer must complete synchronously (or on a faster
  1026. /// scheduler) to avoid the timeout.
  1027. ///
  1028. /// - parameters:
  1029. /// - interval: Number of seconds to wait for `self` to complete.
  1030. /// - error: Error to send with `failed` event if `self` is not completed
  1031. /// when `interval` passes.
  1032. /// - scheduler: A scheduler to deliver error on.
  1033. ///
  1034. /// - returns: A producer that sends events for at most `interval` seconds,
  1035. /// then, if not `completed` - sends `error` with `failed` event
  1036. /// on `scheduler`.
  1037. public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> {
  1038. return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
  1039. }
  1040. }
  1041. extension SignalProducerProtocol where Value: OptionalProtocol {
  1042. /// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
  1043. /// values are dropped.
  1044. ///
  1045. /// - returns: A producer that sends only non-nil values.
  1046. public func skipNil() -> SignalProducer<Value.Wrapped, Error> {
  1047. return lift { $0.skipNil() }
  1048. }
  1049. }
  1050. extension SignalProducerProtocol where Value: EventProtocol, Error == NoError {
  1051. /// The inverse of materialize(), this will translate a producer of `Event`
  1052. /// _values_ into a producer of those events themselves.
  1053. ///
  1054. /// - returns: A producer that sends values carried by `self` events.
  1055. public func dematerialize() -> SignalProducer<Value.Value, Value.Error> {
  1056. return lift { $0.dematerialize() }
  1057. }
  1058. }
  1059. extension SignalProducerProtocol where Error == NoError {
  1060. /// Promote a producer that does not generate failures into one that can.
  1061. ///
  1062. /// - note: This does not actually cause failers to be generated for the
  1063. /// given producer, but makes it easier to combine with other
  1064. /// producers that may fail; for example, with operators like
  1065. /// `combineLatestWith`, `zipWith`, `flatten`, etc.
  1066. ///
  1067. /// - parameters:
  1068. /// - _ An `ErrorType`.
  1069. ///
  1070. /// - returns: A producer that has an instantiatable `ErrorType`.
  1071. public func promoteErrors<F: Swift.Error>(_: F.Type) -> SignalProducer<Value, F> {
  1072. return lift { $0.promoteErrors(F.self) }
  1073. }
  1074. /// Forward events from `self` until `interval`. Then if producer isn't
  1075. /// completed yet, fails with `error` on `scheduler`.
  1076. ///
  1077. /// - note: If the interval is 0, the timeout will be scheduled immediately.
  1078. /// The producer must complete synchronously (or on a faster
  1079. /// scheduler) to avoid the timeout.
  1080. ///
  1081. /// - parameters:
  1082. /// - interval: Number of seconds to wait for `self` to complete.
  1083. /// - error: Error to send with `failed` event if `self` is not completed
  1084. /// when `interval` passes.
  1085. /// - scheudler: A scheduler to deliver error on.
  1086. ///
  1087. /// - returns: A producer that sends events for at most `interval` seconds,
  1088. /// then, if not `completed` - sends `error` with `failed` event
  1089. /// on `scheduler`.
  1090. public func timeout<NewError: Swift.Error>(
  1091. after interval: TimeInterval,
  1092. raising error: NewError,
  1093. on scheduler: DateSchedulerProtocol
  1094. ) -> SignalProducer<Value, NewError> {
  1095. return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
  1096. }
  1097. /// Wait for completion of `self`, *then* forward all events from
  1098. /// `replacement`.
  1099. ///
  1100. /// - note: All values sent from `self` are ignored.
  1101. ///
  1102. /// - parameters:
  1103. /// - replacement: A producer to start when `self` completes.
  1104. ///
  1105. /// - returns: A producer that sends events from `self` and then from
  1106. /// `replacement` when `self` completes.
  1107. public func then<U, NewError: Swift.Error>(_ replacement: SignalProducer<U, NewError>) -> SignalProducer<U, NewError> {
  1108. return self
  1109. .promoteErrors(NewError.self)
  1110. .then(replacement)
  1111. }
  1112. /// Apply a failable `operation` to values from `self` with successful
  1113. /// results forwarded on the returned producer and thrown errors sent as
  1114. /// failed events.
  1115. ///
  1116. /// - parameters:
  1117. /// - operation: A failable closure that accepts a value.
  1118. ///
  1119. /// - returns: A producer that forwards successes as `value` events and thrown
  1120. /// errors as `failed` events.
  1121. public func attempt(_ operation: @escaping (Value) throws -> Void) -> SignalProducer<Value, AnyError> {
  1122. return lift { $0.attempt(operation) }
  1123. }
  1124. /// Apply a failable `operation` to values from `self` with successful
  1125. /// results mapped on the returned producer and thrown errors sent as
  1126. /// failed events.
  1127. ///
  1128. /// - parameters:
  1129. /// - operation: A failable closure that accepts a value and attempts to
  1130. /// transform it.
  1131. ///
  1132. /// - returns: A producer that sends successfully mapped values from `self`,
  1133. /// or thrown errors as `failed` events.
  1134. public func attemptMap<U>(_ operation: @escaping (Value) throws -> U) -> SignalProducer<U, AnyError> {
  1135. return lift { $0.attemptMap(operation) }
  1136. }
  1137. }
  1138. extension SignalProducer {
  1139. /// Create a `SignalProducer` that will attempt the given operation once for
  1140. /// each invocation of `start()`.
  1141. ///
  1142. /// Upon success, the started signal will send the resulting value then
  1143. /// complete. Upon failure, the started signal will fail with the error that
  1144. /// occurred.
  1145. ///
  1146. /// - parameters:
  1147. /// - operation: A closure that returns instance of `Result`.
  1148. ///
  1149. /// - returns: A `SignalProducer` that will forward `success`ful `result` as
  1150. /// `value` event and then complete or `failed` event if `result`
  1151. /// is a `failure`.
  1152. public static func attempt(_ operation: @escaping () -> Result<Value, Error>) -> SignalProducer {
  1153. return self.init { observer, disposable in
  1154. operation().analysis(ifSuccess: { value in
  1155. observer.send(value: value)
  1156. observer.sendCompleted()
  1157. }, ifFailure: { error in
  1158. observer.send(error: error)
  1159. })
  1160. }
  1161. }
  1162. }
  1163. extension SignalProducerProtocol where Error == AnyError {
  1164. /// Create a `SignalProducer` that will attempt the given failable operation once for
  1165. /// each invocation of `start()`.
  1166. ///
  1167. /// Upon success, the started producer will send the resulting value then
  1168. /// complete. Upon failure, the started signal will fail with the error that
  1169. /// occurred.
  1170. ///
  1171. /// - parameters:
  1172. /// - operation: A failable closure.
  1173. ///
  1174. /// - returns: A `SignalProducer` that will forward a success as a `value`
  1175. /// event and then complete or `failed` event if the closure throws.
  1176. public static func attempt(_ operation: @escaping () throws -> Value) -> SignalProducer<Value, Error> {
  1177. return .attempt {
  1178. ReactiveSwift.materialize {
  1179. try operation()
  1180. }
  1181. }
  1182. }
  1183. /// Apply a failable `operation` to values from `self` with successful
  1184. /// results forwarded on the returned producer and thrown errors sent as
  1185. /// failed events.
  1186. ///
  1187. /// - parameters:
  1188. /// - operation: A failable closure that accepts a value.
  1189. ///
  1190. /// - returns: A producer that forwards successes as `value` events and thrown
  1191. /// errors as `failed` events.
  1192. public func attempt(_ operation: @escaping (Value) throws -> Void) -> SignalProducer<Value, AnyError> {
  1193. return lift { $0.attempt(operation) }
  1194. }
  1195. /// Apply a failable `operation` to values from `self` with successful
  1196. /// results mapped on the returned producer and thrown errors sent as
  1197. /// failed events.
  1198. ///
  1199. /// - parameters:
  1200. /// - operation: A failable closure that accepts a value and attempts to
  1201. /// transform it.
  1202. ///
  1203. /// - returns: A producer that sends successfully mapped values from `self`,
  1204. /// or thrown errors as `failed` events.
  1205. public func attemptMap<U>(_ operation: @escaping (Value) throws -> U) -> SignalProducer<U, AnyError> {
  1206. return lift { $0.attemptMap(operation) }
  1207. }
  1208. }
  1209. extension SignalProducerProtocol where Value: Equatable {
  1210. /// Forward only those values from `self` which are not duplicates of the
  1211. /// immedately preceding value.
  1212. ///
  1213. /// - note: The first value is always forwarded.
  1214. ///
  1215. /// - returns: A producer that does not send two equal values sequentially.
  1216. public func skipRepeats() -> SignalProducer<Value, Error> {
  1217. return lift { $0.skipRepeats() }
  1218. }
  1219. }
  1220. extension SignalProducerProtocol {
  1221. /// Forward only those values from `self` that have unique identities across
  1222. /// the set of all values that have been seen.
  1223. ///
  1224. /// - note: This causes the identities to be retained to check for
  1225. /// uniqueness.
  1226. ///
  1227. /// - parameters:
  1228. /// - transform: A closure that accepts a value and returns identity
  1229. /// value.
  1230. ///
  1231. /// - returns: A producer that sends unique values during its lifetime.
  1232. public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> SignalProducer<Value, Error> {
  1233. return lift { $0.uniqueValues(transform) }
  1234. }
  1235. }
  1236. extension SignalProducerProtocol where Value: Hashable {
  1237. /// Forward only those values from `self` that are unique across the set of
  1238. /// all values that have been seen.
  1239. ///
  1240. /// - note: This causes the values to be retained to check for uniqueness.
  1241. /// Providing a function that returns a unique value for each sent
  1242. /// value can help you reduce the memory footprint.
  1243. ///
  1244. /// - returns: A producer that sends unique values during its lifetime.
  1245. public func uniqueValues() -> SignalProducer<Value, Error> {
  1246. return lift { $0.uniqueValues() }
  1247. }
  1248. }
  1249. extension SignalProducerProtocol {
  1250. /// Injects side effects to be performed upon the specified producer events.
  1251. ///
  1252. /// - note: In a composed producer, `starting` is invoked in the reverse
  1253. /// direction of the flow of events.
  1254. ///
  1255. /// - parameters:
  1256. /// - starting: A closure that is invoked before the producer is started.
  1257. /// - started: A closure that is invoked after the producer is started.
  1258. /// - event: A closure that accepts an event and is invoked on every
  1259. /// received event.
  1260. /// - failed: A closure that accepts error object and is invoked for
  1261. /// `failed` event.
  1262. /// - completed: A closure that is invoked for `completed` event.
  1263. /// - interrupted: A closure that is invoked for `interrupted` event.
  1264. /// - terminated: A closure that is invoked for any terminating event.
  1265. /// - disposed: A closure added as disposable when signal completes.
  1266. /// - value: A closure that accepts a value from `value` event.
  1267. ///
  1268. /// - returns: A producer with attached side-effects for given event cases.
  1269. public func on(
  1270. starting: (() -> Void)? = nil,
  1271. started: (() -> Void)? = nil,
  1272. event: ((Event<Value, Error>) -> Void)? = nil,
  1273. failed: ((Error) -> Void)? = nil,
  1274. completed: (() -> Void)? = nil,
  1275. interrupted: (() -> Void)? = nil,
  1276. terminated: (() -> Void)? = nil,
  1277. disposed: (() -> Void)? = nil,
  1278. value: ((Value) -> Void)? = nil
  1279. ) -> SignalProducer<Value, Error> {
  1280. return SignalProducer { observer, compositeDisposable in
  1281. starting?()
  1282. defer { started?() }
  1283. self.startWithSignal { signal, disposable in
  1284. compositeDisposable += disposable
  1285. signal
  1286. .on(
  1287. event: event,
  1288. failed: failed,
  1289. completed: completed,
  1290. interrupted: interrupted,
  1291. terminated: terminated,
  1292. disposed: disposed,
  1293. value: value
  1294. )
  1295. .observe(observer)
  1296. }
  1297. }
  1298. }
  1299. /// Start the returned producer on the given `Scheduler`.
  1300. ///
  1301. /// - note: This implies that any side effects embedded in the producer will
  1302. /// be performed on the given scheduler as well.
  1303. ///
  1304. /// - note: Events may still be sent upon other schedulers — this merely
  1305. /// affects where the `start()` method is run.
  1306. ///
  1307. /// - parameters:
  1308. /// - scheduler: A scheduler to deliver events on.
  1309. ///
  1310. /// - returns: A producer that will deliver events on given `scheduler` when
  1311. /// started.
  1312. public func start(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> {
  1313. return SignalProducer { observer, compositeDisposable in
  1314. compositeDisposable += scheduler.schedule {
  1315. self.startWithSignal { signal, signalDisposable in
  1316. compositeDisposable += signalDisposable
  1317. signal.observe(observer)
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. extension SignalProducerProtocol {
  1324. /// Combines the values of all the given producers, in the manner described by
  1325. /// `combineLatestWith`.
  1326. public static func combineLatest<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> {
  1327. return a.combineLatest(with: b)
  1328. }
  1329. /// Combines the values of all the given producers, in the manner described by
  1330. /// `combineLatestWith`.
  1331. public static func combineLatest<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> {
  1332. return combineLatest(a, b)
  1333. .combineLatest(with: c)
  1334. .map(repack)
  1335. }
  1336. /// Combines the values of all the given producers, in the manner described by
  1337. /// `combineLatestWith`.
  1338. public static func combineLatest<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> {
  1339. return combineLatest(a, b, c)
  1340. .combineLatest(with: d)
  1341. .map(repack)
  1342. }
  1343. /// Combines the values of all the given producers, in the manner described by
  1344. /// `combineLatestWith`.
  1345. public static func combineLatest<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> {
  1346. return combineLatest(a, b, c, d)
  1347. .combineLatest(with: e)
  1348. .map(repack)
  1349. }
  1350. /// Combines the values of all the given producers, in the manner described by
  1351. /// `combineLatestWith`.
  1352. public static func combineLatest<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> {
  1353. return combineLatest(a, b, c, d, e)
  1354. .combineLatest(with: f)
  1355. .map(repack)
  1356. }
  1357. /// Combines the values of all the given producers, in the manner described by
  1358. /// `combineLatestWith`.
  1359. public static func combineLatest<B, C, D, E, F, G>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> {
  1360. return combineLatest(a, b, c, d, e, f)
  1361. .combineLatest(with: g)
  1362. .map(repack)
  1363. }
  1364. /// Combines the values of all the given producers, in the manner described by
  1365. /// `combineLatestWith`.
  1366. public static func combineLatest<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> {
  1367. return combineLatest(a, b, c, d, e, f, g)
  1368. .combineLatest(with: h)
  1369. .map(repack)
  1370. }
  1371. /// Combines the values of all the given producers, in the manner described by
  1372. /// `combineLatestWith`.
  1373. public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> {
  1374. return combineLatest(a, b, c, d, e, f, g, h)
  1375. .combineLatest(with: i)
  1376. .map(repack)
  1377. }
  1378. /// Combines the values of all the given producers, in the manner described by
  1379. /// `combineLatestWith`.
  1380. public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> {
  1381. return combineLatest(a, b, c, d, e, f, g, h, i)
  1382. .combineLatest(with: j)
  1383. .map(repack)
  1384. }
  1385. /// Combines the values of all the given producers, in the manner described by
  1386. /// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty.
  1387. public static func combineLatest<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error>
  1388. where S.Iterator.Element == SignalProducer<Value, Error>
  1389. {
  1390. var generator = producers.makeIterator()
  1391. if let first = generator.next() {
  1392. let initial = first.map { [$0] }
  1393. return IteratorSequence(generator).reduce(initial) { producer, next in
  1394. producer.combineLatest(with: next).map { $0.0 + [$0.1] }
  1395. }
  1396. }
  1397. return .empty
  1398. }
  1399. /// Zips the values of all the given producers, in the manner described by
  1400. /// `zipWith`.
  1401. public static func zip<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> {
  1402. return a.zip(with: b)
  1403. }
  1404. /// Zips the values of all the given producers, in the manner described by
  1405. /// `zipWith`.
  1406. public static func zip<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> {
  1407. return zip(a, b)
  1408. .zip(with: c)
  1409. .map(repack)
  1410. }
  1411. /// Zips the values of all the given producers, in the manner described by
  1412. /// `zipWith`.
  1413. public static func zip<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> {
  1414. return zip(a, b, c)
  1415. .zip(with: d)
  1416. .map(repack)
  1417. }
  1418. /// Zips the values of all the given producers, in the manner described by
  1419. /// `zipWith`.
  1420. public static func zip<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> {
  1421. return zip(a, b, c, d)
  1422. .zip(with: e)
  1423. .map(repack)
  1424. }
  1425. /// Zips the values of all the given producers, in the manner described by
  1426. /// `zipWith`.
  1427. public static func zip<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> {
  1428. return zip(a, b, c, d, e)
  1429. .zip(with: f)
  1430. .map(repack)
  1431. }
  1432. /// Zips the values of all the given producers, in the manner described by
  1433. /// `zipWith`.
  1434. public static func zip<B, C, D, E, F, G>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> {
  1435. return zip(a, b, c, d, e, f)
  1436. .zip(with: g)
  1437. .map(repack)
  1438. }
  1439. /// Zips the values of all the given producers, in the manner described by
  1440. /// `zipWith`.
  1441. public static func zip<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> {
  1442. return zip(a, b, c, d, e, f, g)
  1443. .zip(with: h)
  1444. .map(repack)
  1445. }
  1446. /// Zips the values of all the given producers, in the manner described by
  1447. /// `zipWith`.
  1448. public static func zip<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> {
  1449. return zip(a, b, c, d, e, f, g, h)
  1450. .zip(with: i)
  1451. .map(repack)
  1452. }
  1453. /// Zips the values of all the given producers, in the manner described by
  1454. /// `zipWith`.
  1455. public static func zip<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, 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>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> {
  1456. return zip(a, b, c, d, e, f, g, h, i)
  1457. .zip(with: j)
  1458. .map(repack)
  1459. }
  1460. /// Zips the values of all the given producers, in the manner described by
  1461. /// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
  1462. public static func zip<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error>
  1463. where S.Iterator.Element == SignalProducer<Value, Error>
  1464. {
  1465. var generator = producers.makeIterator()
  1466. if let first = generator.next() {
  1467. let initial = first.map { [$0] }
  1468. return IteratorSequence(generator).reduce(initial) { producer, next in
  1469. producer.zip(with: next).map { $0.0 + [$0.1] }
  1470. }
  1471. }
  1472. return .empty
  1473. }
  1474. }
  1475. extension SignalProducerProtocol {
  1476. /// Repeat `self` a total of `count` times. In other words, start producer
  1477. /// `count` number of times, each one after previously started producer
  1478. /// completes.
  1479. ///
  1480. /// - note: Repeating `1` time results in an equivalent signal producer.
  1481. ///
  1482. /// - note: Repeating `0` times results in a producer that instantly
  1483. /// completes.
  1484. ///
  1485. /// - parameters:
  1486. /// - count: Number of repetitions.
  1487. ///
  1488. /// - returns: A signal producer start sequentially starts `self` after
  1489. /// previously started producer completes.
  1490. public func `repeat`(_ count: Int) -> SignalProducer<Value, Error> {
  1491. precondition(count >= 0)
  1492. if count == 0 {
  1493. return .empty
  1494. } else if count == 1 {
  1495. return producer
  1496. }
  1497. return SignalProducer { observer, disposable in
  1498. let serialDisposable = SerialDisposable()
  1499. disposable += serialDisposable
  1500. func iterate(_ current: Int) {
  1501. self.startWithSignal { signal, signalDisposable in
  1502. serialDisposable.inner = signalDisposable
  1503. signal.observe { event in
  1504. if case .completed = event {
  1505. let remainingTimes = current - 1
  1506. if remainingTimes > 0 {
  1507. iterate(remainingTimes)
  1508. } else {
  1509. observer.sendCompleted()
  1510. }
  1511. } else {
  1512. observer.action(event)
  1513. }
  1514. }
  1515. }
  1516. }
  1517. iterate(count)
  1518. }
  1519. }
  1520. /// Ignore failures up to `count` times.
  1521. ///
  1522. /// - precondition: `count` must be non-negative integer.
  1523. ///
  1524. /// - parameters:
  1525. /// - count: Number of retries.
  1526. ///
  1527. /// - returns: A signal producer that restarts up to `count` times.
  1528. public func retry(upTo count: Int) -> SignalProducer<Value, Error> {
  1529. precondition(count >= 0)
  1530. if count == 0 {
  1531. return producer
  1532. } else {
  1533. return flatMapError { _ in
  1534. self.retry(upTo: count - 1)
  1535. }
  1536. }
  1537. }
  1538. /// Wait for completion of `self`, *then* forward all events from
  1539. /// `replacement`. Any failure or interruption sent from `self` is
  1540. /// forwarded immediately, in which case `replacement` will not be started,
  1541. /// and none of its events will be be forwarded.
  1542. ///
  1543. /// - note: All values sent from `self` are ignored.
  1544. ///
  1545. /// - parameters:
  1546. /// - replacement: A producer to start when `self` completes.
  1547. ///
  1548. /// - returns: A producer that sends events from `self` and then from
  1549. /// `replacement` when `self` completes.
  1550. public func then<U>(_ replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> {
  1551. return SignalProducer<U, Error> { observer, observerDisposable in
  1552. self.startWithSignal { signal, signalDisposable in
  1553. observerDisposable += signalDisposable
  1554. signal.observe { event in
  1555. switch event {
  1556. case let .failed(error):
  1557. observer.send(error: error)
  1558. case .completed:
  1559. observerDisposable += replacement.start(observer)
  1560. case .interrupted:
  1561. observer.sendInterrupted()
  1562. case .value:
  1563. break
  1564. }
  1565. }
  1566. }
  1567. }
  1568. }
  1569. /// Wait for completion of `self`, *then* forward all events from
  1570. /// `replacement`. Any failure or interruption sent from `self` is
  1571. /// forwarded immediately, in which case `replacement` will not be started,
  1572. /// and none of its events will be be forwarded.
  1573. ///
  1574. /// - note: All values sent from `self` are ignored.
  1575. ///
  1576. /// - parameters:
  1577. /// - replacement: A producer to start when `self` completes.
  1578. ///
  1579. /// - returns: A producer that sends events from `self` and then from
  1580. /// `replacement` when `self` completes.
  1581. public func then<U>(_ replacement: SignalProducer<U, NoError>) -> SignalProducer<U, Error> {
  1582. return self.then(replacement.promoteErrors(Error.self))
  1583. }
  1584. /// Start the producer, then block, waiting for the first value.
  1585. ///
  1586. /// When a single value or error is sent, the returned `Result` will
  1587. /// represent those cases. However, when no values are sent, `nil` will be
  1588. /// returned.
  1589. ///
  1590. /// - returns: Result when single `value` or `failed` event is received.
  1591. /// `nil` when no events are received.
  1592. public func first() -> Result<Value, Error>? {
  1593. return take(first: 1).single()
  1594. }
  1595. /// Start the producer, then block, waiting for events: `value` and
  1596. /// `completed`.
  1597. ///
  1598. /// When a single value or error is sent, the returned `Result` will
  1599. /// represent those cases. However, when no values are sent, or when more
  1600. /// than one value is sent, `nil` will be returned.
  1601. ///
  1602. /// - returns: Result when single `value` or `failed` event is received.
  1603. /// `nil` when 0 or more than 1 events are received.
  1604. public func single() -> Result<Value, Error>? {
  1605. let semaphore = DispatchSemaphore(value: 0)
  1606. var result: Result<Value, Error>?
  1607. take(first: 2).start { event in
  1608. switch event {
  1609. case let .value(value):
  1610. if result != nil {
  1611. // Move into failure state after recieving another value.
  1612. result = nil
  1613. return
  1614. }
  1615. result = .success(value)
  1616. case let .failed(error):
  1617. result = .failure(error)
  1618. semaphore.signal()
  1619. case .completed, .interrupted:
  1620. semaphore.signal()
  1621. }
  1622. }
  1623. semaphore.wait()
  1624. return result
  1625. }
  1626. /// Start the producer, then block, waiting for the last value.
  1627. ///
  1628. /// When a single value or error is sent, the returned `Result` will
  1629. /// represent those cases. However, when no values are sent, `nil` will be
  1630. /// returned.
  1631. ///
  1632. /// - returns: Result when single `value` or `failed` event is received.
  1633. /// `nil` when no events are received.
  1634. public func last() -> Result<Value, Error>? {
  1635. return take(last: 1).single()
  1636. }
  1637. /// Starts the producer, then blocks, waiting for completion.
  1638. ///
  1639. /// When a completion or error is sent, the returned `Result` will represent
  1640. /// those cases.
  1641. ///
  1642. /// - returns: Result when single `completion` or `failed` event is
  1643. /// received.
  1644. public func wait() -> Result<(), Error> {
  1645. return then(SignalProducer<(), Error>(value: ())).last() ?? .success(())
  1646. }
  1647. /// Creates a new `SignalProducer` that will multicast values emitted by
  1648. /// the underlying producer, up to `capacity`.
  1649. /// This means that all clients of this `SignalProducer` will see the same
  1650. /// version of the emitted values/errors.
  1651. ///
  1652. /// The underlying `SignalProducer` will not be started until `self` is
  1653. /// started for the first time. When subscribing to this producer, all
  1654. /// previous values (up to `capacity`) will be emitted, followed by any new
  1655. /// values.
  1656. ///
  1657. /// If you find yourself needing *the current value* (the last buffered
  1658. /// value) you should consider using `PropertyType` instead, which, unlike
  1659. /// this operator, will guarantee at compile time that there's always a
  1660. /// buffered value. This operator is not recommended in most cases, as it
  1661. /// will introduce an implicit relationship between the original client and
  1662. /// the rest, so consider alternatives like `PropertyType`, or representing
  1663. /// your stream using a `Signal` instead.
  1664. ///
  1665. /// This operator is only recommended when you absolutely need to introduce
  1666. /// a layer of caching in front of another `SignalProducer`.
  1667. ///
  1668. /// - precondtion: `capacity` must be non-negative integer.
  1669. ///
  1670. /// - parameters:
  1671. /// - capcity: Number of values to hold.
  1672. ///
  1673. /// - returns: A caching producer that will hold up to last `capacity`
  1674. /// values.
  1675. public func replayLazily(upTo capacity: Int) -> SignalProducer<Value, Error> {
  1676. precondition(capacity >= 0, "Invalid capacity: \(capacity)")
  1677. // This will go "out of scope" when the returned `SignalProducer` goes
  1678. // out of scope. This lets us know when we're supposed to dispose the
  1679. // underlying producer. This is necessary because `struct`s don't have
  1680. // `deinit`.
  1681. let lifetimeToken = Lifetime.Token()
  1682. let lifetime = Lifetime(lifetimeToken)
  1683. let state = Atomic(ReplayState<Value, Error>(upTo: capacity))
  1684. let start: Atomic<(() -> Void)?> = Atomic {
  1685. // Start the underlying producer.
  1686. self
  1687. .take(during: lifetime)
  1688. .start { event in
  1689. let observers: Bag<Signal<Value, Error>.Observer>? = state.modify { state in
  1690. defer { state.enqueue(event) }
  1691. return state.observers
  1692. }
  1693. observers?.forEach { $0.action(event) }
  1694. }
  1695. }
  1696. return SignalProducer { observer, disposable in
  1697. // Don't dispose of the original producer until all observers
  1698. // have terminated.
  1699. disposable += { _ = lifetimeToken }
  1700. while true {
  1701. var result: Result<RemovalToken?, ReplayError<Value>>!
  1702. state.modify {
  1703. result = $0.observe(observer)
  1704. }
  1705. switch result! {
  1706. case let .success(token):
  1707. if let token = token {
  1708. disposable += {
  1709. state.modify {
  1710. $0.removeObserver(using: token)
  1711. }
  1712. }
  1713. }
  1714. // Start the underlying producer if it has never been started.
  1715. start.swap(nil)?()
  1716. // Terminate the replay loop.
  1717. return
  1718. case let .failure(error):
  1719. error.values.forEach(observer.send(value:))
  1720. }
  1721. }
  1722. }
  1723. }
  1724. }
  1725. /// Represents a recoverable error of an observer not being ready for an
  1726. /// attachment to a `ReplayState`, and the observer should replay the supplied
  1727. /// values before attempting to observe again.
  1728. private struct ReplayError<Value>: Error {
  1729. /// The values that should be replayed by the observer.
  1730. let values: [Value]
  1731. }
  1732. private struct ReplayState<Value, Error: Swift.Error> {
  1733. let capacity: Int
  1734. /// All cached values.
  1735. var values: [Value] = []
  1736. /// A termination event emitted by the underlying producer.
  1737. ///
  1738. /// This will be nil if termination has not occurred.
  1739. var terminationEvent: Event<Value, Error>?
  1740. /// The observers currently attached to the caching producer, or `nil` if the
  1741. /// caching producer was terminated.
  1742. var observers: Bag<Signal<Value, Error>.Observer>? = Bag()
  1743. /// The set of in-flight replay buffers.
  1744. var replayBuffers: [ObjectIdentifier: [Value]] = [:]
  1745. /// Initialize the replay state.
  1746. ///
  1747. /// - parameters:
  1748. /// - capacity: The maximum amount of values which can be cached by the
  1749. /// replay state.
  1750. init(upTo capacity: Int) {
  1751. self.capacity = capacity
  1752. }
  1753. /// Attempt to observe the replay state.
  1754. ///
  1755. /// - warning: Repeatedly observing the replay state with the same observer
  1756. /// should be avoided.
  1757. ///
  1758. /// - parameters:
  1759. /// - observer: The observer to be registered.
  1760. ///
  1761. /// - returns:
  1762. /// If the observer is successfully attached, a `Result.success` with the
  1763. /// corresponding removal token would be returned. Otherwise, a
  1764. /// `Result.failure` with a `ReplayError` would be returned.
  1765. mutating func observe(_ observer: Signal<Value, Error>.Observer) -> Result<RemovalToken?, ReplayError<Value>> {
  1766. // Since the only use case is `replayLazily`, which always creates a unique
  1767. // `Observer` for every produced signal, we can use the ObjectIdentifier of
  1768. // the `Observer` to track them directly.
  1769. let id = ObjectIdentifier(observer)
  1770. switch replayBuffers[id] {
  1771. case .none where !values.isEmpty:
  1772. // No in-flight replay buffers was found, but the `ReplayState` has one or
  1773. // more cached values in the `ReplayState`. The observer should replay
  1774. // them before attempting to observe again.
  1775. replayBuffers[id] = []
  1776. return .failure(ReplayError(values: values))
  1777. case let .some(buffer) where !buffer.isEmpty:
  1778. // An in-flight replay buffer was found with one or more buffered values.
  1779. // The observer should replay them before attempting to observe again.
  1780. defer { replayBuffers[id] = [] }
  1781. return .failure(ReplayError(values: buffer))
  1782. case let .some(buffer) where buffer.isEmpty:
  1783. // Since an in-flight but empty replay buffer was found, the observer is
  1784. // ready to be attached to the `ReplayState`.
  1785. replayBuffers.removeValue(forKey: id)
  1786. default:
  1787. // No values has to be replayed. The observer is ready to be attached to
  1788. // the `ReplayState`.
  1789. break
  1790. }
  1791. if let event = terminationEvent {
  1792. observer.action(event)
  1793. }
  1794. return .success(observers?.insert(observer))
  1795. }
  1796. /// Enqueue the supplied event to the replay state.
  1797. ///
  1798. /// - parameter:
  1799. /// - event: The event to be cached.
  1800. mutating func enqueue(_ event: Event<Value, Error>) {
  1801. switch event {
  1802. case let .value(value):
  1803. for key in replayBuffers.keys {
  1804. replayBuffers[key]!.append(value)
  1805. }
  1806. switch capacity {
  1807. case 0:
  1808. // With a capacity of zero, `state.values` can never be filled.
  1809. break
  1810. case 1:
  1811. values = [value]
  1812. default:
  1813. values.append(value)
  1814. let overflow = values.count - capacity
  1815. if overflow > 0 {
  1816. values.removeFirst(overflow)
  1817. }
  1818. }
  1819. case .completed, .failed, .interrupted:
  1820. // Disconnect all observers and prevent future attachments.
  1821. terminationEvent = event
  1822. observers = nil
  1823. }
  1824. }
  1825. /// Remove the observer represented by the supplied token.
  1826. ///
  1827. /// - parameters:
  1828. /// - token: The token of the observer to be removed.
  1829. mutating func removeObserver(using token: RemovalToken) {
  1830. observers?.remove(using: token)
  1831. }
  1832. }
  1833. /// Create a repeating timer of the given interval, with a reasonable default
  1834. /// leeway, sending updates on the given scheduler.
  1835. ///
  1836. /// - note: This timer will never complete naturally, so all invocations of
  1837. /// `start()` must be disposed to avoid leaks.
  1838. ///
  1839. /// - precondition: Interval must be non-negative number.
  1840. ///
  1841. /// - note: If you plan to specify an `interval` value greater than 200,000
  1842. /// seconds, use `timer(interval:on:leeway:)` instead
  1843. /// and specify your own `leeway` value to avoid potential overflow.
  1844. ///
  1845. /// - parameters:
  1846. /// - interval: An interval between invocations.
  1847. /// - scheduler: A scheduler to deliver events on.
  1848. ///
  1849. /// - returns: A producer that sends `NSDate` values every `interval` seconds.
  1850. public func timer(interval: DispatchTimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Date, NoError> {
  1851. // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
  1852. // at least 10% of the timer interval.
  1853. return timer(interval: interval, on: scheduler, leeway: interval * 0.1)
  1854. }
  1855. /// Creates a repeating timer of the given interval, sending updates on the
  1856. /// given scheduler.
  1857. ///
  1858. /// - note: This timer will never complete naturally, so all invocations of
  1859. /// `start()` must be disposed to avoid leaks.
  1860. ///
  1861. /// - precondition: Interval must be non-negative number.
  1862. ///
  1863. /// - precondition: Leeway must be non-negative number.
  1864. ///
  1865. /// - parameters:
  1866. /// - interval: An interval between invocations.
  1867. /// - scheduler: A scheduler to deliver events on.
  1868. /// - leeway: Interval leeway. Apple's "Power Efficiency Guide for Mac Apps"
  1869. /// recommends a leeway of at least 10% of the timer interval.
  1870. ///
  1871. /// - returns: A producer that sends `NSDate` values every `interval` seconds.
  1872. public func timer(interval: DispatchTimeInterval, on scheduler: DateSchedulerProtocol, leeway: DispatchTimeInterval) -> SignalProducer<Date, NoError> {
  1873. precondition(interval.timeInterval >= 0)
  1874. precondition(leeway.timeInterval >= 0)
  1875. return SignalProducer { observer, compositeDisposable in
  1876. compositeDisposable += scheduler.schedule(after: scheduler.currentDate.addingTimeInterval(interval),
  1877. interval: interval,
  1878. leeway: leeway,
  1879. action: { observer.send(value: scheduler.currentDate) })
  1880. }
  1881. }