Created
December 4, 2015 00:02
-
-
Save neilpa/5d47d807a2552edff116 to your computer and use it in GitHub Desktop.
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
- (RACSignal*) continueInBackground | |
{ | |
return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) { | |
UIApplication* app = UIApplication.sharedApplication; | |
__block UIBackgroundTaskIdentifier taskID; | |
RACCompoundDisposable* compoundDisposable = [RACCompoundDisposable compoundDisposable]; | |
RACDisposable* backgroundTaskDisposable = [RACDisposable disposableWithBlock:^{ | |
[app endBackgroundTask:taskID]; | |
}]; | |
// To ensure the background task isn't ended before the error or completed event | |
// is delivered we have to remove the background disposable from our compound | |
// disposable. Otherwise, the internal signal executes the disposable before actually | |
// invoking the error or completion blocks. As such, we have to do this dance with | |
// the background disposable. | |
taskID = [app beginBackgroundTaskWithExpirationHandler:^{ | |
NSLog(@"Background task timed out."); | |
[compoundDisposable removeDisposable:backgroundTaskDisposable]; | |
[subscriber sendError:[NSError errorWithDomain:RACSignalErrorDomain code:RACSignalErrorTimedOut userInfo:nil]]; | |
[backgroundTaskDisposable dispose]; | |
}]; | |
RACDisposable* subscriptionDisposable = [self subscribeNext:^(id x) { | |
[subscriber sendNext:x]; | |
} error:^(NSError *error) { | |
[compoundDisposable removeDisposable:backgroundTaskDisposable]; | |
[subscriber sendError:error]; | |
[backgroundTaskDisposable dispose]; | |
} completed:^{ | |
[compoundDisposable removeDisposable:backgroundTaskDisposable]; | |
[subscriber sendCompleted]; | |
[backgroundTaskDisposable dispose]; | |
}]; | |
// Add the background disposable last since it should run after the subscription | |
// is cleaned up. | |
[compoundDisposable addDisposable:subscriptionDisposable]; | |
[compoundDisposable addDisposable:backgroundTaskDisposable]; | |
return compoundDisposable; | |
}] | |
setNameWithFormat:@"[%@] -continueInBackground", self.name]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment