Last active
August 29, 2015 14:24
-
-
Save sharplet/0822ed0c1c1165502c1d to your computer and use it in GitHub Desktop.
Wrapping UIKit background tasks with ReactiveCocoa (http://sharplet.me/post/123363708110/wrapping-uikit-background-tasks-with)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// An API for managing UIKit background tasks by composing signals. | |
@interface UIApplication (SHReactiveBackgroundTask) | |
/// Creates a signal that wraps an underlying signal in a background task. | |
/// Upon subscription, starts a background task, and then automatically ends | |
/// the background task when the underlying signal completes or errors. | |
/// If the background task expires, the subscription to the underlying signal | |
/// will automatically be disposed of. | |
/// | |
/// @note If the call to `-beginBackgroundTaskWithExpirationHandler:` returns | |
/// `UIBackgroundTaskInvalid`, the returned signal will immediately send an error, | |
/// and `signalBlock` will never be invoked. | |
- (RACSignal *)sh_backgroundTaskWithSignal:(RACSignal *(^)(void))signalBlock; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation UIApplication (SHReactiveBackgroundTask) | |
- (RACSignal *)sh_backgroundTaskWithSignal:(RACSignal *(^)(void))signalBlock { | |
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { | |
__block RACDisposable *taskDisposable; | |
UIBackgroundTaskIdentifier taskIdentifier = [self beginBackgroundTaskWithExpirationHandler:^{ | |
[taskDisposable dispose]; | |
}]; | |
if (taskIdentifier == UIBackgroundTaskInvalid) { | |
NSError *error = [NSError errorWithDomain:@"me.sharplet.ReactiveBackgroundTask" code:0 userInfo:@{ | |
NSLocalizedDescriptionKey: @"Running in the background is not possible." | |
}]; | |
[subscriber sendError:error]; | |
return nil; | |
} | |
RACSignal *taskSignal = signalBlock(); | |
taskDisposable = [[taskSignal | |
finally:^{ | |
[self endBackgroundTask:taskIdentifier]; | |
}] | |
subscribe:subscriber]; | |
return taskDisposable; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment