Last active
June 29, 2018 19:36
-
-
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
This file contains hidden or 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
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