RACSignal.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //
  2. // RACSignal.h
  3. // ReactiveObjC
  4. //
  5. // Created by Josh Abernathy on 3/1/12.
  6. // Copyright (c) 2012 GitHub, Inc. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. #import "RACStream.h"
  10. @class RACDisposable;
  11. @class RACScheduler;
  12. @class RACSubject;
  13. @protocol RACSubscriber;
  14. NS_ASSUME_NONNULL_BEGIN
  15. @interface RACSignal<__covariant ValueType> : RACStream
  16. /// Creates a new signal. This is the preferred way to create a new signal
  17. /// operation or behavior.
  18. ///
  19. /// Events can be sent to new subscribers immediately in the `didSubscribe`
  20. /// block, but the subscriber will not be able to dispose of the signal until
  21. /// a RACDisposable is returned from `didSubscribe`. In the case of infinite
  22. /// signals, this won't _ever_ happen if events are sent immediately.
  23. ///
  24. /// To ensure that the signal is disposable, events can be scheduled on the
  25. /// +[RACScheduler currentScheduler] (so that they're deferred, not sent
  26. /// immediately), or they can be sent in the background. The RACDisposable
  27. /// returned by the `didSubscribe` block should cancel any such scheduling or
  28. /// asynchronous work.
  29. ///
  30. /// didSubscribe - Called when the signal is subscribed to. The new subscriber is
  31. /// passed in. You can then manually control the <RACSubscriber> by
  32. /// sending it -sendNext:, -sendError:, and -sendCompleted,
  33. /// as defined by the operation you're implementing. This block
  34. /// should return a RACDisposable which cancels any ongoing work
  35. /// triggered by the subscription, and cleans up any resources or
  36. /// disposables created as part of it. When the disposable is
  37. /// disposed of, the signal must not send any more events to the
  38. /// `subscriber`. If no cleanup is necessary, return nil.
  39. ///
  40. /// **Note:** The `didSubscribe` block is called every time a new subscriber
  41. /// subscribes. Any side effects within the block will thus execute once for each
  42. /// subscription, not necessarily on one thread, and possibly even
  43. /// simultaneously!
  44. + (RACSignal<ValueType> *)createSignal:(RACDisposable * _Nullable (^)(id<RACSubscriber> subscriber))didSubscribe;
  45. /// Returns a signal that immediately sends the given error.
  46. + (RACSignal<ValueType> *)error:(nullable NSError *)error;
  47. /// Returns a signal that never completes.
  48. + (RACSignal<ValueType> *)never;
  49. /// Immediately schedules the given block on the given scheduler. The block is
  50. /// given a subscriber to which it can send events.
  51. ///
  52. /// scheduler - The scheduler on which `block` will be scheduled and results
  53. /// delivered. Cannot be nil.
  54. /// block - The block to invoke. Cannot be NULL.
  55. ///
  56. /// Returns a signal which will send all events sent on the subscriber given to
  57. /// `block`. All events will be sent on `scheduler` and it will replay any missed
  58. /// events to new subscribers.
  59. + (RACSignal<ValueType> *)startEagerlyWithScheduler:(RACScheduler *)scheduler block:(void (^)(id<RACSubscriber> subscriber))block;
  60. /// Invokes the given block only on the first subscription. The block is given a
  61. /// subscriber to which it can send events.
  62. ///
  63. /// Note that disposing of the subscription to the returned signal will *not*
  64. /// dispose of the underlying subscription. If you need that behavior, see
  65. /// -[RACMulticastConnection autoconnect]. The underlying subscription will never
  66. /// be disposed of. Because of this, `block` should never return an infinite
  67. /// signal since there would be no way of ending it.
  68. ///
  69. /// scheduler - The scheduler on which the block should be scheduled. Note that
  70. /// if given +[RACScheduler immediateScheduler], the block will be
  71. /// invoked synchronously on the first subscription. Cannot be nil.
  72. /// block - The block to invoke on the first subscription. Cannot be NULL.
  73. ///
  74. /// Returns a signal which will pass through the events sent to the subscriber
  75. /// given to `block` and replay any missed events to new subscribers.
  76. + (RACSignal<ValueType> *)startLazilyWithScheduler:(RACScheduler *)scheduler block:(void (^)(id<RACSubscriber> subscriber))block;
  77. @end
  78. @interface RACSignal<__covariant ValueType> (RACStream)
  79. /// Returns a signal that immediately sends the given value and then completes.
  80. + (RACSignal<ValueType> *)return:(nullable ValueType)value;
  81. /// Returns a signal that immediately completes.
  82. + (RACSignal<ValueType> *)empty;
  83. /// A block which accepts a value from a RACSignal and returns a new signal.
  84. ///
  85. /// Setting `stop` to `YES` will cause the bind to terminate after the returned
  86. /// value. Returning `nil` will result in immediate termination.
  87. typedef RACSignal * _Nullable (^RACSignalBindBlock)(ValueType _Nullable value, BOOL *stop);
  88. /// Lazily binds a block to the values in the receiver.
  89. ///
  90. /// This should only be used if you need to terminate the bind early, or close
  91. /// over some state. -flattenMap: is more appropriate for all other cases.
  92. ///
  93. /// block - A block returning a RACSignalBindBlock. This block will be invoked
  94. /// each time the bound signal is re-evaluated. This block must not be
  95. /// nil or return nil.
  96. ///
  97. /// Returns a new signal which represents the combined result of all lazy
  98. /// applications of `block`.
  99. - (RACSignal *)bind:(RACSignalBindBlock (^)(void))block;
  100. /// Subscribes to `signal` when the source signal completes.
  101. - (RACSignal *)concat:(RACSignal *)signal;
  102. /// Zips the values in the receiver with those of the given signal to create
  103. /// RACTuples.
  104. ///
  105. /// The first `next` of each signal will be combined, then the second `next`,
  106. /// and so forth, until either signal completes or errors.
  107. ///
  108. /// signal - The signal to zip with. This must not be `nil`.
  109. ///
  110. /// Returns a new signal of RACTuples, representing the combined values of the
  111. /// two signals. Any error from one of the original signals will be forwarded on
  112. /// the returned signal.
  113. - (RACSignal *)zipWith:(RACSignal *)signal;
  114. @end
  115. /// Redeclarations of operations built on the RACStream primitives with more
  116. /// precise ValueType information.
  117. ///
  118. /// In cases where the ValueType of the result of the operation is not able to
  119. /// be inferred, the ValueType is erased in the result.
  120. ///
  121. /// In cases where instancetype is a valid return type, the operation is not
  122. /// redeclared here.
  123. @interface RACSignal<__covariant ValueType> (RACStreamOperations)
  124. /// Maps `block` across the values in the receiver and flattens the result.
  125. ///
  126. /// Note that operators applied _after_ -flattenMap: behave differently from
  127. /// operators _within_ -flattenMap:. See the Examples section below.
  128. ///
  129. /// This corresponds to the `SelectMany` method in Rx.
  130. ///
  131. /// block - A block which accepts the values in the receiver and returns a new
  132. /// instance of the receiver's class. Returning `nil` from this block is
  133. /// equivalent to returning an empty signal.
  134. ///
  135. /// Examples
  136. ///
  137. /// [signal flattenMap:^(id x) {
  138. /// // Logs each time a returned signal completes.
  139. /// return [[RACSignal return:x] logCompleted];
  140. /// }];
  141. ///
  142. /// [[signal
  143. /// flattenMap:^(id x) {
  144. /// return [RACSignal return:x];
  145. /// }]
  146. /// // Logs only once, when all of the signals complete.
  147. /// logCompleted];
  148. ///
  149. /// Returns a new signal which represents the combined signals resulting from
  150. /// mapping `block`.
  151. - (RACSignal *)flattenMap:(__kindof RACSignal * _Nullable (^)(ValueType _Nullable value))block;
  152. /// Flattens a signal of signals.
  153. ///
  154. /// This corresponds to the `Merge` method in Rx.
  155. ///
  156. /// Returns a signal consisting of the combined signals obtained from the
  157. /// receiver.
  158. - (RACSignal *)flatten;
  159. /// Maps `block` across the values in the receiver.
  160. ///
  161. /// This corresponds to the `Select` method in Rx.
  162. ///
  163. /// Returns a new signal with the mapped values.
  164. - (RACSignal *)map:(id _Nullable (^)(ValueType _Nullable value))block;
  165. /// Replaces each value in the receiver with the given object.
  166. ///
  167. /// Returns a new signal which includes the given object once for each value in
  168. /// the receiver.
  169. - (RACSignal *)mapReplace:(nullable id)object;
  170. /// Filters out values in the receiver that don't pass the given test.
  171. ///
  172. /// This corresponds to the `Where` method in Rx.
  173. ///
  174. /// Returns a new signal with only those values that passed.
  175. - (RACSignal<ValueType> *)filter:(BOOL (^)(ValueType _Nullable value))block;
  176. /// Filters out values in the receiver that equal (via -isEqual:) the provided
  177. /// value.
  178. ///
  179. /// value - The value can be `nil`, in which case it ignores `nil` values.
  180. ///
  181. /// Returns a new signal containing only the values which did not compare equal
  182. /// to `value`.
  183. - (RACSignal<ValueType> *)ignore:(nullable ValueType)value;
  184. /// Unpacks each RACTuple in the receiver and maps the values to a new value.
  185. ///
  186. /// reduceBlock - The block which reduces each RACTuple's values into one value.
  187. /// It must take as many arguments as the number of tuple elements
  188. /// to process. Each argument will be an object argument. The
  189. /// return value must be an object. This argument cannot be nil.
  190. ///
  191. /// Returns a new signal of reduced tuple values.
  192. - (RACSignal *)reduceEach:(id _Nullable (^)())reduceBlock;
  193. /// Returns a signal consisting of `value`, followed by the values in the
  194. /// receiver.
  195. - (RACSignal<ValueType> *)startWith:(nullable ValueType)value;
  196. /// Skips the first `skipCount` values in the receiver.
  197. ///
  198. /// Returns the receiver after skipping the first `skipCount` values. If
  199. /// `skipCount` is greater than the number of values in the signal, an empty
  200. /// signal is returned.
  201. - (RACSignal<ValueType> *)skip:(NSUInteger)skipCount;
  202. /// Returns a signal of the first `count` values in the receiver. If `count` is
  203. /// greater than or equal to the number of values in the signal, a signal
  204. /// equivalent to the receiver is returned.
  205. - (RACSignal<ValueType> *)take:(NSUInteger)count;
  206. /// Zips the values in the given signals to create RACTuples.
  207. ///
  208. /// The first value of each signals will be combined, then the second value, and
  209. /// so forth, until at least one of the signals is exhausted.
  210. ///
  211. /// signals - The signals to combine. If this collection is empty, the returned
  212. /// signal will be empty.
  213. ///
  214. /// Returns a new signal containing RACTuples of the zipped values from the
  215. /// signals.
  216. + (RACSignal<ValueType> *)zip:(id<NSFastEnumeration>)signals;
  217. /// Zips signals using +zip:, then reduces the resulting tuples into a single
  218. /// value using -reduceEach:
  219. ///
  220. /// signals - The signals to combine. If this collection is empty, the
  221. /// returned signal will be empty.
  222. /// reduceBlock - The block which reduces the values from all the signals
  223. /// into one value. It must take as many arguments as the
  224. /// number of signals given. Each argument will be an object
  225. /// argument. The return value must be an object. This argument
  226. /// must not be nil.
  227. ///
  228. /// Example:
  229. ///
  230. /// [RACSignal zip:@[ stringSignal, intSignal ]
  231. /// reduce:^(NSString *string, NSNumber *number) {
  232. /// return [NSString stringWithFormat:@"%@: %@", string, number];
  233. /// }];
  234. ///
  235. /// Returns a new signal containing the results from each invocation of
  236. /// `reduceBlock`.
  237. + (RACSignal<ValueType> *)zip:(id<NSFastEnumeration>)signals reduce:(id _Nullable (^)())reduceBlock;
  238. /// Returns a signal obtained by concatenating `signals` in order.
  239. + (RACSignal<ValueType> *)concat:(id<NSFastEnumeration>)signals;
  240. /// Combines values in the receiver from left to right using the given block.
  241. ///
  242. /// The algorithm proceeds as follows:
  243. ///
  244. /// 1. `startingValue` is passed into the block as the `running` value, and the
  245. /// first element of the receiver is passed into the block as the `next` value.
  246. /// 2. The result of the invocation is added to the returned signal.
  247. /// 3. The result of the invocation (`running`) and the next element of the
  248. /// receiver (`next`) is passed into `block`.
  249. /// 4. Steps 2 and 3 are repeated until all values have been processed.
  250. ///
  251. /// startingValue - The value to be combined with the first element of the
  252. /// receiver. This value may be `nil`.
  253. /// reduceBlock - The block that describes how to combine values of the
  254. /// receiver. If the receiver is empty, this block will never be
  255. /// invoked. Cannot be nil.
  256. ///
  257. /// Examples
  258. ///
  259. /// RACSequence *numbers = @[ @1, @2, @3, @4 ].rac_sequence;
  260. ///
  261. /// // Contains 1, 3, 6, 10
  262. /// RACSequence *sums = [numbers scanWithStart:@0 reduce:^(NSNumber *sum, NSNumber *next) {
  263. /// return @(sum.integerValue + next.integerValue);
  264. /// }];
  265. ///
  266. /// Returns a new signal that consists of each application of `reduceBlock`. If
  267. /// the receiver is empty, an empty signal is returned.
  268. - (RACSignal *)scanWithStart:(nullable id)startingValue reduce:(id _Nullable (^)(id _Nullable running, ValueType _Nullable next))reduceBlock;
  269. /// Combines values in the receiver from left to right using the given block
  270. /// which also takes zero-based index of the values.
  271. ///
  272. /// startingValue - The value to be combined with the first element of the
  273. /// receiver. This value may be `nil`.
  274. /// reduceBlock - The block that describes how to combine values of the
  275. /// receiver. This block takes zero-based index value as the last
  276. /// parameter. If the receiver is empty, this block will never
  277. /// be invoked. Cannot be nil.
  278. ///
  279. /// Returns a new signal that consists of each application of `reduceBlock`. If
  280. /// the receiver is empty, an empty signal is returned.
  281. - (RACSignal *)scanWithStart:(nullable id)startingValue reduceWithIndex:(id _Nullable (^)(id _Nullable running, ValueType _Nullable next, NSUInteger index))reduceBlock;
  282. /// Combines each previous and current value into one object.
  283. ///
  284. /// This method is similar to -scanWithStart:reduce:, but only ever operates on
  285. /// the previous and current values (instead of the whole signal), and does not
  286. /// pass the return value of `reduceBlock` into the next invocation of it.
  287. ///
  288. /// start - The value passed into `reduceBlock` as `previous` for the
  289. /// first value.
  290. /// reduceBlock - The block that combines the previous value and the current
  291. /// value to create the reduced value. Cannot be nil.
  292. ///
  293. /// Examples
  294. ///
  295. /// RACSignal<NSNumber *> *numbers = [@[ @1, @2, @3, @4 ].rac_sequence
  296. /// signalWithScheduler:RACScheduler.immediateScheduler];
  297. ///
  298. /// // Contains 1, 3, 5, 7
  299. /// RACSignal *sums = [numbers combinePreviousWithStart:@0 reduce:^(NSNumber *previous, NSNumber *next) {
  300. /// return @(previous.integerValue + next.integerValue);
  301. /// }];
  302. ///
  303. /// Returns a new signal consisting of the return values from each application of
  304. /// `reduceBlock`.
  305. - (RACSignal *)combinePreviousWithStart:(nullable ValueType)start reduce:(id _Nullable (^)(ValueType _Nullable previous, ValueType _Nullable current))reduceBlock;
  306. /// Takes values until the given block returns `YES`.
  307. ///
  308. /// Returns a signal of the initial values in the receiver that fail `predicate`.
  309. /// If `predicate` never returns `YES`, a signal equivalent to the receiver is
  310. /// returned.
  311. - (RACSignal<ValueType> *)takeUntilBlock:(BOOL (^)(ValueType _Nullable x))predicate;
  312. /// Takes values until the given block returns `NO`.
  313. ///
  314. /// Returns a signal of the initial values in the receiver that pass `predicate`.
  315. /// If `predicate` never returns `NO`, a signal equivalent to the receiver is
  316. /// returned.
  317. - (RACSignal<ValueType> *)takeWhileBlock:(BOOL (^)(ValueType _Nullable x))predicate;
  318. /// Skips values until the given block returns `YES`.
  319. ///
  320. /// Returns a signal containing the values of the receiver that follow any
  321. /// initial values failing `predicate`. If `predicate` never returns `YES`,
  322. /// an empty signal is returned.
  323. - (RACSignal<ValueType> *)skipUntilBlock:(BOOL (^)(ValueType _Nullable x))predicate;
  324. /// Skips values until the given block returns `NO`.
  325. ///
  326. /// Returns a signal containing the values of the receiver that follow any
  327. /// initial values passing `predicate`. If `predicate` never returns `NO`, an
  328. /// empty signal is returned.
  329. - (RACSignal<ValueType> *)skipWhileBlock:(BOOL (^)(ValueType _Nullable x))predicate;
  330. /// Returns a signal of values for which -isEqual: returns NO when compared to the
  331. /// previous value.
  332. - (RACSignal<ValueType> *)distinctUntilChanged;
  333. @end
  334. @interface RACSignal<__covariant ValueType> (Subscription)
  335. /// Subscribes `subscriber` to changes on the receiver. The receiver defines which
  336. /// events it actually sends and in what situations the events are sent.
  337. ///
  338. /// Subscription will always happen on a valid RACScheduler. If the
  339. /// +[RACScheduler currentScheduler] cannot be determined at the time of
  340. /// subscription (e.g., because the calling code is running on a GCD queue or
  341. /// NSOperationQueue), subscription will occur on a private background scheduler.
  342. /// On the main thread, subscriptions will always occur immediately, with a
  343. /// +[RACScheduler currentScheduler] of +[RACScheduler mainThreadScheduler].
  344. ///
  345. /// This method must be overridden by any subclasses.
  346. ///
  347. /// Returns nil or a disposable. You can call -[RACDisposable dispose] if you
  348. /// need to end your subscription before it would "naturally" end, either by
  349. /// completing or erroring. Once the disposable has been disposed, the subscriber
  350. /// won't receive any more events from the subscription.
  351. - (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber;
  352. /// Convenience method to subscribe to the `next` event.
  353. ///
  354. /// This corresponds to `IObserver<T>.OnNext` in Rx.
  355. - (RACDisposable *)subscribeNext:(void (^)(ValueType _Nullable x))nextBlock;
  356. /// Convenience method to subscribe to the `next` and `completed` events.
  357. - (RACDisposable *)subscribeNext:(void (^)(ValueType _Nullable x))nextBlock completed:(void (^)(void))completedBlock;
  358. /// Convenience method to subscribe to the `next`, `completed`, and `error` events.
  359. - (RACDisposable *)subscribeNext:(void (^)(ValueType _Nullable x))nextBlock error:(void (^)(NSError * _Nullable error))errorBlock completed:(void (^)(void))completedBlock;
  360. /// Convenience method to subscribe to `error` events.
  361. ///
  362. /// This corresponds to the `IObserver<T>.OnError` in Rx.
  363. - (RACDisposable *)subscribeError:(void (^)(NSError * _Nullable error))errorBlock;
  364. /// Convenience method to subscribe to `completed` events.
  365. ///
  366. /// This corresponds to the `IObserver<T>.OnCompleted` in Rx.
  367. - (RACDisposable *)subscribeCompleted:(void (^)(void))completedBlock;
  368. /// Convenience method to subscribe to `next` and `error` events.
  369. - (RACDisposable *)subscribeNext:(void (^)(ValueType _Nullable x))nextBlock error:(void (^)(NSError * _Nullable error))errorBlock;
  370. /// Convenience method to subscribe to `error` and `completed` events.
  371. - (RACDisposable *)subscribeError:(void (^)(NSError * _Nullable error))errorBlock completed:(void (^)(void))completedBlock;
  372. @end
  373. /// Additional methods to assist with debugging.
  374. @interface RACSignal<__covariant ValueType> (Debugging)
  375. /// Logs all events that the receiver sends.
  376. - (RACSignal<ValueType> *)logAll;
  377. /// Logs each `next` that the receiver sends.
  378. - (RACSignal<ValueType> *)logNext;
  379. /// Logs any error that the receiver sends.
  380. - (RACSignal<ValueType> *)logError;
  381. /// Logs any `completed` event that the receiver sends.
  382. - (RACSignal<ValueType> *)logCompleted;
  383. @end
  384. /// Additional methods to assist with unit testing.
  385. ///
  386. /// **These methods should never ship in production code.**
  387. @interface RACSignal<__covariant ValueType> (Testing)
  388. /// Spins the main run loop for a short while, waiting for the receiver to send a `next`.
  389. ///
  390. /// **Because this method executes the run loop recursively, it should only be used
  391. /// on the main thread, and only from a unit test.**
  392. ///
  393. /// defaultValue - Returned if the receiver completes or errors before sending
  394. /// a `next`, or if the method times out. This argument may be
  395. /// nil.
  396. /// success - If not NULL, set to whether the receiver completed
  397. /// successfully.
  398. /// error - If not NULL, set to any error that occurred.
  399. ///
  400. /// Returns the first value received, or `defaultValue` if no value is received
  401. /// before the signal finishes or the method times out.
  402. - (nullable ValueType)asynchronousFirstOrDefault:(nullable ValueType)defaultValue success:(nullable BOOL *)success error:(NSError * _Nullable * _Nullable)error;
  403. /// Spins the main run loop for a short while, waiting for the receiver to complete.
  404. ///
  405. /// **Because this method executes the run loop recursively, it should only be used
  406. /// on the main thread, and only from a unit test.**
  407. ///
  408. /// error - If not NULL, set to any error that occurs.
  409. ///
  410. /// Returns whether the signal completed successfully before timing out. If NO,
  411. /// `error` will be set to any error that occurred.
  412. - (BOOL)asynchronouslyWaitUntilCompleted:(NSError * _Nullable * _Nullable)error;
  413. @end
  414. NS_ASSUME_NONNULL_END