RACSignal.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. //
  2. // RACSignal.m
  3. // ReactiveObjC
  4. //
  5. // Created by Josh Abernathy on 3/15/12.
  6. // Copyright (c) 2012 GitHub, Inc. All rights reserved.
  7. //
  8. #import "RACSignal.h"
  9. #import "RACCompoundDisposable.h"
  10. #import "RACDisposable.h"
  11. #import "RACDynamicSignal.h"
  12. #import "RACEmptySignal.h"
  13. #import "RACErrorSignal.h"
  14. #import "RACMulticastConnection.h"
  15. #import "RACReplaySubject.h"
  16. #import "RACReturnSignal.h"
  17. #import "RACScheduler.h"
  18. #import "RACSerialDisposable.h"
  19. #import "RACSignal+Operations.h"
  20. #import "RACSubject.h"
  21. #import "RACSubscriber+Private.h"
  22. #import "RACTuple.h"
  23. #import <libkern/OSAtomic.h>
  24. @implementation RACSignal
  25. #pragma mark Lifecycle
  26. + (RACSignal *)createSignal:(RACDisposable * (^)(id<RACSubscriber> subscriber))didSubscribe {
  27. return [RACDynamicSignal createSignal:didSubscribe];
  28. }
  29. + (RACSignal *)error:(NSError *)error {
  30. return [RACErrorSignal error:error];
  31. }
  32. + (RACSignal *)never {
  33. return [[self createSignal:^ RACDisposable * (id<RACSubscriber> subscriber) {
  34. return nil;
  35. }] setNameWithFormat:@"+never"];
  36. }
  37. + (RACSignal *)startEagerlyWithScheduler:(RACScheduler *)scheduler block:(void (^)(id<RACSubscriber> subscriber))block {
  38. NSCParameterAssert(scheduler != nil);
  39. NSCParameterAssert(block != NULL);
  40. RACSignal *signal = [self startLazilyWithScheduler:scheduler block:block];
  41. // Subscribe to force the lazy signal to call its block.
  42. [[signal publish] connect];
  43. return [signal setNameWithFormat:@"+startEagerlyWithScheduler: %@ block:", scheduler];
  44. }
  45. + (RACSignal *)startLazilyWithScheduler:(RACScheduler *)scheduler block:(void (^)(id<RACSubscriber> subscriber))block {
  46. NSCParameterAssert(scheduler != nil);
  47. NSCParameterAssert(block != NULL);
  48. RACMulticastConnection *connection = [[RACSignal
  49. createSignal:^ id (id<RACSubscriber> subscriber) {
  50. block(subscriber);
  51. return nil;
  52. }]
  53. multicast:[RACReplaySubject subject]];
  54. return [[[RACSignal
  55. createSignal:^ id (id<RACSubscriber> subscriber) {
  56. [connection.signal subscribe:subscriber];
  57. [connection connect];
  58. return nil;
  59. }]
  60. subscribeOn:scheduler]
  61. setNameWithFormat:@"+startLazilyWithScheduler: %@ block:", scheduler];
  62. }
  63. #pragma mark NSObject
  64. - (NSString *)description {
  65. return [NSString stringWithFormat:@"<%@: %p> name: %@", self.class, self, self.name];
  66. }
  67. @end
  68. @implementation RACSignal (RACStream)
  69. + (RACSignal *)empty {
  70. return [RACEmptySignal empty];
  71. }
  72. + (RACSignal *)return:(id)value {
  73. return [RACReturnSignal return:value];
  74. }
  75. - (RACSignal *)bind:(RACSignalBindBlock (^)(void))block {
  76. NSCParameterAssert(block != NULL);
  77. /*
  78. * -bind: should:
  79. *
  80. * 1. Subscribe to the original signal of values.
  81. * 2. Any time the original signal sends a value, transform it using the binding block.
  82. * 3. If the binding block returns a signal, subscribe to it, and pass all of its values through to the subscriber as they're received.
  83. * 4. If the binding block asks the bind to terminate, complete the _original_ signal.
  84. * 5. When _all_ signals complete, send completed to the subscriber.
  85. *
  86. * If any signal sends an error at any point, send that to the subscriber.
  87. */
  88. return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {
  89. RACSignalBindBlock bindingBlock = block();
  90. __block volatile int32_t signalCount = 1; // indicates self
  91. RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable];
  92. void (^completeSignal)(RACDisposable *) = ^(RACDisposable *finishedDisposable) {
  93. if (OSAtomicDecrement32Barrier(&signalCount) == 0) {
  94. [subscriber sendCompleted];
  95. [compoundDisposable dispose];
  96. } else {
  97. [compoundDisposable removeDisposable:finishedDisposable];
  98. }
  99. };
  100. void (^addSignal)(RACSignal *) = ^(RACSignal *signal) {
  101. OSAtomicIncrement32Barrier(&signalCount);
  102. RACSerialDisposable *selfDisposable = [[RACSerialDisposable alloc] init];
  103. [compoundDisposable addDisposable:selfDisposable];
  104. RACDisposable *disposable = [signal subscribeNext:^(id x) {
  105. [subscriber sendNext:x];
  106. } error:^(NSError *error) {
  107. [compoundDisposable dispose];
  108. [subscriber sendError:error];
  109. } completed:^{
  110. @autoreleasepool {
  111. completeSignal(selfDisposable);
  112. }
  113. }];
  114. selfDisposable.disposable = disposable;
  115. };
  116. @autoreleasepool {
  117. RACSerialDisposable *selfDisposable = [[RACSerialDisposable alloc] init];
  118. [compoundDisposable addDisposable:selfDisposable];
  119. RACDisposable *bindingDisposable = [self subscribeNext:^(id x) {
  120. // Manually check disposal to handle synchronous errors.
  121. if (compoundDisposable.disposed) return;
  122. BOOL stop = NO;
  123. id signal = bindingBlock(x, &stop);
  124. @autoreleasepool {
  125. if (signal != nil) addSignal(signal);
  126. if (signal == nil || stop) {
  127. [selfDisposable dispose];
  128. completeSignal(selfDisposable);
  129. }
  130. }
  131. } error:^(NSError *error) {
  132. [compoundDisposable dispose];
  133. [subscriber sendError:error];
  134. } completed:^{
  135. @autoreleasepool {
  136. completeSignal(selfDisposable);
  137. }
  138. }];
  139. selfDisposable.disposable = bindingDisposable;
  140. }
  141. return compoundDisposable;
  142. }] setNameWithFormat:@"[%@] -bind:", self.name];
  143. }
  144. - (RACSignal *)concat:(RACSignal *)signal {
  145. return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {
  146. RACCompoundDisposable *compoundDisposable = [[RACCompoundDisposable alloc] init];
  147. RACDisposable *sourceDisposable = [self subscribeNext:^(id x) {
  148. [subscriber sendNext:x];
  149. } error:^(NSError *error) {
  150. [subscriber sendError:error];
  151. } completed:^{
  152. RACDisposable *concattedDisposable = [signal subscribe:subscriber];
  153. [compoundDisposable addDisposable:concattedDisposable];
  154. }];
  155. [compoundDisposable addDisposable:sourceDisposable];
  156. return compoundDisposable;
  157. }] setNameWithFormat:@"[%@] -concat: %@", self.name, signal];
  158. }
  159. - (RACSignal *)zipWith:(RACSignal *)signal {
  160. NSCParameterAssert(signal != nil);
  161. return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {
  162. __block BOOL selfCompleted = NO;
  163. NSMutableArray *selfValues = [NSMutableArray array];
  164. __block BOOL otherCompleted = NO;
  165. NSMutableArray *otherValues = [NSMutableArray array];
  166. void (^sendCompletedIfNecessary)(void) = ^{
  167. @synchronized (selfValues) {
  168. BOOL selfEmpty = (selfCompleted && selfValues.count == 0);
  169. BOOL otherEmpty = (otherCompleted && otherValues.count == 0);
  170. if (selfEmpty || otherEmpty) [subscriber sendCompleted];
  171. }
  172. };
  173. void (^sendNext)(void) = ^{
  174. @synchronized (selfValues) {
  175. if (selfValues.count == 0) return;
  176. if (otherValues.count == 0) return;
  177. RACTuple *tuple = RACTuplePack(selfValues[0], otherValues[0]);
  178. [selfValues removeObjectAtIndex:0];
  179. [otherValues removeObjectAtIndex:0];
  180. [subscriber sendNext:tuple];
  181. sendCompletedIfNecessary();
  182. }
  183. };
  184. RACDisposable *selfDisposable = [self subscribeNext:^(id x) {
  185. @synchronized (selfValues) {
  186. [selfValues addObject:x ?: RACTupleNil.tupleNil];
  187. sendNext();
  188. }
  189. } error:^(NSError *error) {
  190. [subscriber sendError:error];
  191. } completed:^{
  192. @synchronized (selfValues) {
  193. selfCompleted = YES;
  194. sendCompletedIfNecessary();
  195. }
  196. }];
  197. RACDisposable *otherDisposable = [signal subscribeNext:^(id x) {
  198. @synchronized (selfValues) {
  199. [otherValues addObject:x ?: RACTupleNil.tupleNil];
  200. sendNext();
  201. }
  202. } error:^(NSError *error) {
  203. [subscriber sendError:error];
  204. } completed:^{
  205. @synchronized (selfValues) {
  206. otherCompleted = YES;
  207. sendCompletedIfNecessary();
  208. }
  209. }];
  210. return [RACDisposable disposableWithBlock:^{
  211. [selfDisposable dispose];
  212. [otherDisposable dispose];
  213. }];
  214. }] setNameWithFormat:@"[%@] -zipWith: %@", self.name, signal];
  215. }
  216. @end
  217. @implementation RACSignal (Subscription)
  218. - (RACDisposable *)subscribe:(id<RACSubscriber>)subscriber {
  219. NSCAssert(NO, @"This method must be overridden by subclasses");
  220. return nil;
  221. }
  222. - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock {
  223. NSCParameterAssert(nextBlock != NULL);
  224. RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL];
  225. return [self subscribe:o];
  226. }
  227. - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock completed:(void (^)(void))completedBlock {
  228. NSCParameterAssert(nextBlock != NULL);
  229. NSCParameterAssert(completedBlock != NULL);
  230. RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:completedBlock];
  231. return [self subscribe:o];
  232. }
  233. - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock completed:(void (^)(void))completedBlock {
  234. NSCParameterAssert(nextBlock != NULL);
  235. NSCParameterAssert(errorBlock != NULL);
  236. NSCParameterAssert(completedBlock != NULL);
  237. RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:errorBlock completed:completedBlock];
  238. return [self subscribe:o];
  239. }
  240. - (RACDisposable *)subscribeError:(void (^)(NSError *error))errorBlock {
  241. NSCParameterAssert(errorBlock != NULL);
  242. RACSubscriber *o = [RACSubscriber subscriberWithNext:NULL error:errorBlock completed:NULL];
  243. return [self subscribe:o];
  244. }
  245. - (RACDisposable *)subscribeCompleted:(void (^)(void))completedBlock {
  246. NSCParameterAssert(completedBlock != NULL);
  247. RACSubscriber *o = [RACSubscriber subscriberWithNext:NULL error:NULL completed:completedBlock];
  248. return [self subscribe:o];
  249. }
  250. - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock error:(void (^)(NSError *error))errorBlock {
  251. NSCParameterAssert(nextBlock != NULL);
  252. NSCParameterAssert(errorBlock != NULL);
  253. RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:errorBlock completed:NULL];
  254. return [self subscribe:o];
  255. }
  256. - (RACDisposable *)subscribeError:(void (^)(NSError *))errorBlock completed:(void (^)(void))completedBlock {
  257. NSCParameterAssert(completedBlock != NULL);
  258. NSCParameterAssert(errorBlock != NULL);
  259. RACSubscriber *o = [RACSubscriber subscriberWithNext:NULL error:errorBlock completed:completedBlock];
  260. return [self subscribe:o];
  261. }
  262. @end
  263. @implementation RACSignal (Debugging)
  264. - (RACSignal *)logAll {
  265. return [[[self logNext] logError] logCompleted];
  266. }
  267. - (RACSignal *)logNext {
  268. return [[self doNext:^(id x) {
  269. NSLog(@"%@ next: %@", self, x);
  270. }] setNameWithFormat:@"%@", self.name];
  271. }
  272. - (RACSignal *)logError {
  273. return [[self doError:^(NSError *error) {
  274. NSLog(@"%@ error: %@", self, error);
  275. }] setNameWithFormat:@"%@", self.name];
  276. }
  277. - (RACSignal *)logCompleted {
  278. return [[self doCompleted:^{
  279. NSLog(@"%@ completed", self);
  280. }] setNameWithFormat:@"%@", self.name];
  281. }
  282. @end
  283. @implementation RACSignal (Testing)
  284. static const NSTimeInterval RACSignalAsynchronousWaitTimeout = 10;
  285. - (id)asynchronousFirstOrDefault:(id)defaultValue success:(BOOL *)success error:(NSError **)error {
  286. return [self asynchronousFirstOrDefault:defaultValue success:success error:error timeout:RACSignalAsynchronousWaitTimeout];
  287. }
  288. - (id)asynchronousFirstOrDefault:(id)defaultValue success:(BOOL *)success error:(NSError **)error timeout:(NSTimeInterval)timeout {
  289. NSCAssert([NSThread isMainThread], @"%s should only be used from the main thread", __func__);
  290. __block id result = defaultValue;
  291. __block BOOL done = NO;
  292. // Ensures that we don't pass values across thread boundaries by reference.
  293. __block NSError *localError;
  294. __block BOOL localSuccess = YES;
  295. [[[[self
  296. take:1]
  297. timeout:timeout onScheduler:[RACScheduler scheduler]]
  298. deliverOn:RACScheduler.mainThreadScheduler]
  299. subscribeNext:^(id x) {
  300. result = x;
  301. done = YES;
  302. } error:^(NSError *e) {
  303. if (!done) {
  304. localSuccess = NO;
  305. localError = e;
  306. done = YES;
  307. }
  308. } completed:^{
  309. done = YES;
  310. }];
  311. do {
  312. [NSRunLoop.mainRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
  313. } while (!done);
  314. if (success != NULL) *success = localSuccess;
  315. if (error != NULL) *error = localError;
  316. return result;
  317. }
  318. - (BOOL)asynchronouslyWaitUntilCompleted:(NSError **)error timeout:(NSTimeInterval)timeout {
  319. BOOL success = NO;
  320. [[self ignoreValues] asynchronousFirstOrDefault:nil success:&success error:error timeout:timeout];
  321. return success;
  322. }
  323. - (BOOL)asynchronouslyWaitUntilCompleted:(NSError **)error {
  324. return [self asynchronouslyWaitUntilCompleted:error timeout:RACSignalAsynchronousWaitTimeout];
  325. }
  326. @end