Skip to content

Instantly share code, notes, and snippets.

@TheCodedSelf
Last active June 29, 2018 19:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheCodedSelf/f269d70dc358903c29cee125d028027c to your computer and use it in GitHub Desktop.
Save TheCodedSelf/f269d70dc358903c29cee125d028027c to your computer and use it in GitHub Desktop.
RxSwift: An example of causing one observable to rely on the output of another
import RxSwift
func submit(number: Int) {
let validateAndPerformServiceCallIfSuccessful = performValidation(numberThatShouldBeEven: number)
.flatMap { () -> Observable<Void> in
print("Validated successfully")
return performServiceCall() // For any .next events from performValidation, perform the service call
}
// By subscribing, validation is performed and the service call is executed for any .next events from performValidation
validateAndPerformServiceCallIfSuccessful.subscribe(onNext: { _ in
print("Service call was a success!")
}, onError: { _ in
print("Something went wrong.")
})
}
private func performValidation(numberThatShouldBeEven: Int) -> Observable<Void> {
print("Performing validation")
return numberThatShouldBeEven % 2 == 0 ?
Observable.just(()) : // Validation was successful
Observable.error(NSError(domain: "com.thecodedself.rxswift", code: 0, userInfo: nil)) // Validation failed
}
private func performServiceCall() -> Observable<Void> {
print("Performing service call")
return Observable.just(()) // Return the results from the service
}
submit(number: 2)
print("--------")
submit(number: 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment