SignalProducer.swift 78 KB

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