RXSwift 用户输入错误和继续 [英] RXSwift User input on error and continuation

查看:31
本文介绍了RXSwift 用户输入错误和继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 RX 很陌生,我正在尝试了解如何在出现需要用户输入的错误后继续执行任务.

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.

一个具体的例子是两因素身份验证.我们有一个身份验证服务和一个受保护的资源.登录后,我们从 auth-service 收到一个 LOA-2(使用的用户名和密码)令牌.尝试从受保护资源中获取数据时,我们收到一条错误消息,指出我们需要 LOA-3(双因素).因此,我们必须从用户那里获取输入,将其发送到 auth-service,获取新令牌 (LOA-3) 并使用新令牌重试我们的 fetch 调用.

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 :)

推荐答案

您将需要使用 catchError 函数从错误中恢复并启动一个新的 observable 来启动替代行为.

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)

然后获取令牌.

let loaToken = credentials.flatMap { serverLogin($0, $1) }.catchError { error in 
    if error == loa3Error {
        return getLOA3Data().flatMap { loa3ServerLogin($0) }
    }
    else {
        throw error
    }
}

getLOA3Data 是一个返回 Observable 的函数,该 Observable 包含 loa3 身份验证所需的数据.

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.

这篇关于RXSwift 用户输入错误和继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆