Skip to content

Instantly share code, notes, and snippets.

@andynovak12
Last active May 8, 2018 14:37
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 andynovak12/2016954a811a7473b743fbce28071445 to your computer and use it in GitHub Desktop.
Save andynovak12/2016954a811a7473b743fbce28071445 to your computer and use it in GitHub Desktop.
Wrapping Asynchronous Functions In ReactiveSwift
// Mock External Library Definitions
func mockAsyncFunction(completion: @escaping (String?, MockError?) -> Void ) {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
completion("mockAsyncFunction completed successfully", nil)
// uncomment the below line and comment the one above to return an error
// completion(nil, MockError.asyncError)
}
}
enum MockError: Error, LocalizedError {
case asyncError
var errorDescription: String? {
switch self {
case .asyncError:
return "Async had an error"
}
}
}
// Simple Use of Asynchronous Library Function
mockAsyncFunction { (optionalReturnedString, optionalReturnedError) in
if let returnedString = optionalReturnedString {
print(returnedString)
} else if let returnedError = optionalReturnedError {
print(returnedError)
}
}
// Wrapping Asynchronous Function
func wrappedFunction() -> SignalProducer<String, MockError> {
return SignalProducer { observer, disposable in
mockAsyncFunction { (optionalReturnedString, optionalReturnedError) in
if let returnedString = optionalReturnedString {
observer.send(value: returnedString)
observer.sendCompleted()
} else if let returnedError = optionalReturnedError {
observer.send(error: returnedError)
}
}
}
}
// Simple Use of Asynchronous ReactiveSwift Function
wrappedFunction().startWithResult { result in
if let returnedString = result.value {
print(returnedString)
} else if let returnedError = result.error {
print(returnedError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment