Wrapping Asynchronous Functions In ReactiveSwift
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
// 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