PrimitiveSequence.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //
  2. // PrimitiveSequence.swift
  3. // RxSwift
  4. //
  5. // Created by Krunoslav Zaher on 3/5/17.
  6. // Copyright © 2017 Krunoslav Zaher. All rights reserved.
  7. //
  8. /// Observable sequences containing 0 or 1 element.
  9. public struct PrimitiveSequence<Trait, Element> {
  10. let source: Observable<Element>
  11. init(raw: Observable<Element>) {
  12. self.source = raw
  13. }
  14. }
  15. /// Observable sequences containing 0 or 1 element
  16. public protocol PrimitiveSequenceType {
  17. /// Additional constraints
  18. associatedtype Trait
  19. /// Sequence element type
  20. associatedtype Element
  21. @available(*, deprecated, renamed: "Trait")
  22. typealias TraitType = Trait
  23. @available(*, deprecated, renamed: "Element")
  24. typealias ElementType = Element
  25. // Converts `self` to primitive sequence.
  26. ///
  27. /// - returns: Observable sequence that represents `self`.
  28. var primitiveSequence: PrimitiveSequence<Trait, Element> { get }
  29. }
  30. extension PrimitiveSequence: PrimitiveSequenceType {
  31. // Converts `self` to primitive sequence.
  32. ///
  33. /// - returns: Observable sequence that represents `self`.
  34. public var primitiveSequence: PrimitiveSequence<Trait, Element> {
  35. return self
  36. }
  37. }
  38. extension PrimitiveSequence: ObservableConvertibleType {
  39. /// Converts `self` to `Observable` sequence.
  40. ///
  41. /// - returns: Observable sequence that represents `self`.
  42. public func asObservable() -> Observable<Element> {
  43. return self.source
  44. }
  45. }
  46. extension PrimitiveSequence {
  47. /**
  48. Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
  49. - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
  50. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
  51. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
  52. */
  53. public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
  54. -> PrimitiveSequence<Trait, Element> {
  55. return PrimitiveSequence(raw: Observable.deferred {
  56. try observableFactory().asObservable()
  57. })
  58. }
  59. /**
  60. Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
  61. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
  62. - parameter dueTime: Relative time shift of the source by.
  63. - parameter scheduler: Scheduler to run the subscription delay timer on.
  64. - returns: the source Observable shifted in time by the specified delay.
  65. */
  66. public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
  67. -> PrimitiveSequence<Trait, Element> {
  68. return PrimitiveSequence(raw: self.primitiveSequence.source.delay(dueTime, scheduler: scheduler))
  69. }
  70. /**
  71. Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
  72. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
  73. - parameter dueTime: Relative time shift of the subscription.
  74. - parameter scheduler: Scheduler to run the subscription delay timer on.
  75. - returns: Time-shifted sequence.
  76. */
  77. public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
  78. -> PrimitiveSequence<Trait, Element> {
  79. return PrimitiveSequence(raw: self.source.delaySubscription(dueTime, scheduler: scheduler))
  80. }
  81. /**
  82. Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
  83. This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
  84. actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
  85. - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
  86. - parameter scheduler: Scheduler to notify observers on.
  87. - returns: The source sequence whose observations happen on the specified scheduler.
  88. */
  89. public func observeOn(_ scheduler: ImmediateSchedulerType)
  90. -> PrimitiveSequence<Trait, Element> {
  91. return PrimitiveSequence(raw: self.source.observeOn(scheduler))
  92. }
  93. /**
  94. Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
  95. scheduler.
  96. This operation is not commonly used.
  97. This only performs the side-effects of subscription and unsubscription on the specified scheduler.
  98. In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
  99. - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
  100. - parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
  101. - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
  102. */
  103. public func subscribeOn(_ scheduler: ImmediateSchedulerType)
  104. -> PrimitiveSequence<Trait, Element> {
  105. return PrimitiveSequence(raw: self.source.subscribeOn(scheduler))
  106. }
  107. /**
  108. Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
  109. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
  110. - parameter handler: Error handler function, producing another observable sequence.
  111. - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
  112. */
  113. public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
  114. -> PrimitiveSequence<Trait, Element> {
  115. return PrimitiveSequence(raw: self.source.catchError { try handler($0).asObservable() })
  116. }
  117. /**
  118. If the initial subscription to the observable sequence emits an error event, try repeating it up to the specified number of attempts (inclusive of the initial attempt) or until is succeeds. For example, if you want to retry a sequence once upon failure, you should use retry(2) (once for the initial attempt, and once for the retry).
  119. - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
  120. - parameter maxAttemptCount: Maximum number of times to attempt the sequence subscription.
  121. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
  122. */
  123. public func retry(_ maxAttemptCount: Int)
  124. -> PrimitiveSequence<Trait, Element> {
  125. return PrimitiveSequence(raw: self.source.retry(maxAttemptCount))
  126. }
  127. /**
  128. Repeats the source observable sequence on error when the notifier emits a next value.
  129. If the source observable errors and the notifier completes, it will complete the source sequence.
  130. - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
  131. - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
  132. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
  133. */
  134. public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
  135. -> PrimitiveSequence<Trait, Element> {
  136. return PrimitiveSequence(raw: self.source.retryWhen(notificationHandler))
  137. }
  138. /**
  139. Repeats the source observable sequence on error when the notifier emits a next value.
  140. If the source observable errors and the notifier completes, it will complete the source sequence.
  141. - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
  142. - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
  143. - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
  144. */
  145. public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
  146. -> PrimitiveSequence<Trait, Element> {
  147. return PrimitiveSequence(raw: self.source.retryWhen(notificationHandler))
  148. }
  149. /**
  150. Prints received events for all observers on standard output.
  151. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
  152. - parameter identifier: Identifier that is printed together with event description to standard output.
  153. - parameter trimOutput: Should output be trimmed to max 40 characters.
  154. - returns: An observable sequence whose events are printed to standard output.
  155. */
  156. public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
  157. -> PrimitiveSequence<Trait, Element> {
  158. return PrimitiveSequence(raw: self.source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
  159. }
  160. /**
  161. Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
  162. - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
  163. - parameter resourceFactory: Factory function to obtain a resource object.
  164. - parameter primitiveSequenceFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
  165. - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
  166. */
  167. public static func using<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
  168. -> PrimitiveSequence<Trait, Element> {
  169. return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<Element> in
  170. return try primitiveSequenceFactory(resource).asObservable()
  171. }))
  172. }
  173. /**
  174. Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
  175. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
  176. - parameter dueTime: Maximum duration between values before a timeout occurs.
  177. - parameter scheduler: Scheduler to run the timeout timer on.
  178. - returns: An observable sequence with a `RxError.timeout` in case of a timeout.
  179. */
  180. public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
  181. -> PrimitiveSequence<Trait, Element> {
  182. return PrimitiveSequence<Trait, Element>(raw: self.primitiveSequence.source.timeout(dueTime, scheduler: scheduler))
  183. }
  184. /**
  185. Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
  186. - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
  187. - parameter dueTime: Maximum duration between values before a timeout occurs.
  188. - parameter other: Sequence to return in case of a timeout.
  189. - parameter scheduler: Scheduler to run the timeout timer on.
  190. - returns: The source sequence switching to the other sequence in case of a timeout.
  191. */
  192. public func timeout(_ dueTime: RxTimeInterval,
  193. other: PrimitiveSequence<Trait, Element>,
  194. scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
  195. return PrimitiveSequence<Trait, Element>(raw: self.primitiveSequence.source.timeout(dueTime, other: other.source, scheduler: scheduler))
  196. }
  197. }
  198. extension PrimitiveSequenceType where Element: RxAbstractInteger
  199. {
  200. /**
  201. Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
  202. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
  203. - parameter dueTime: Relative time at which to produce the first value.
  204. - parameter scheduler: Scheduler to run timers on.
  205. - returns: An observable sequence that produces a value after due time has elapsed and then each period.
  206. */
  207. public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
  208. -> PrimitiveSequence<Trait, Element> {
  209. return PrimitiveSequence(raw: Observable<Element>.timer(dueTime, scheduler: scheduler))
  210. }
  211. }