Skip to content

Instantly share code, notes, and snippets.

@sharplet
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/0822ed0c1c1165502c1d to your computer and use it in GitHub Desktop.
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)
/// 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
@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