问题
I'm quite new to RX and I'm trying to understand how I can continue a task, after an error which requires user input.
A concrete example would be two factor authentication.. We have an auth-service and a protected resource. Logging in, we receive from the auth-service a LOA-2 (username&password used) token. trying to fetch data from the protected resource we receive an error stating we need LOA-3 (two-factor). So we have to get the input from the user, send it to the auth-service, get a new token (LOA-3) und retry our fetch call with the new token.
There are a lot of examples for logins, but I can't wrap my head around continuing a chain, which requires user input.
Any ideas? Thanks :)
回答1:
You will need to use the catchError
function to recover from the error and start a new observable that initiates the alternative behavior.
So for example, you need a producer that gets the username and password...
let credentialInput = Observable.combineLatest(usernameLabel.rx_text, passwordLabel.rx_text)
You will likely want to wait until the user taps a "login" button...
let credentials = credentialInput.sample(loginButton.rx_tap)
Then get the token.
let loaToken = credentials.flatMap { serverLogin($0, $1) }.catchError { error in
if error == loa3Error {
return getLOA3Data().flatMap { loa3ServerLogin($0) }
}
else {
throw error
}
}
getLOA3Data
is a function that returns an Observable that contains the data needed for the loa3 authentication.
The above is, of course, pseudo code, but I expect it will give you a good idea about how to wrap your head around the problem.
来源:https://stackoverflow.com/questions/35841054/rxswift-user-input-on-error-and-continuation