Reputation: 839
Anybody can help me with this? I have this small code:
getUserDetailsApi().flatMap(){users in
return getScoreApi(users[0])
}.subscribe(
onCompleted: {
print("Done")
},
onError: {
// which of the two APIs get an error?
})
I call two APIs here, in the getUserDetailsApi I want to invoke an error when it failed to get the user details or something went wrong and skip the getScoreApi. Same on the getScoreApi if it fails to get the score of the user it will throw a different error.
is there a way I can throw the said errors on flatMap()?. Note that the two observable must be execute in sequence order and these errors has different message
Upvotes: 0
Views: 9085
Reputation: 2326
You should throw the error in getUserDetailsApi()
and getScoreApi()
.
Example:
func getUserDetailsApi() -> Observable<[User]> {
return Observable.create { observer in
// Your api call
// ...
// Probably you get the users array or an error.
if (error) {
observer.onError(YourError.UserDetailsError) // <- Your error
} else {
observer.onNext(users)
observer.onCompleted()
}
return Disposables.create {
// your dispose
}
}
}
And the same for getScoreApi()
. Then, if one of them fails, the flatMap
will fail.
getUserDetailsApi().flatMap(){users in
return getScoreApi(users[0])
}.subscribe(
onCompleted: {
print("Done")
},
onError: {
switch error{
case .userDetailsError:
// ...
case .otherError:
// ...
}
})
Upvotes: 2