简体   繁体   中英

How to display and recover from API errors in ViewController when using RxSwift

I'm trying to figure out how I can retry an API call at the ViewController layer when dealing with an RxSwift stream. I understand that I can either wrap my errors in an Element or I can return a stream Error . In either case, it's not at all clear how I can "retry" the operation the discretion of the user (eg after putting up an alert).

If I wrap the error, how can/should I communicate back "down" to the API layer to attempt a retry? If I don't wrap the error, I have two questions: 1) How can I make the retry conditional on the user's response to the alert? and 2) How can/should I "re-initialize" the stream?

The only thing I've been able to come up with is passing back a "retry subject" with the error and having the view controller indicate the retry request by emitting something on the associated observable (ie assign a value to the subject) which would in term be associated with the API stream. That seems awfully convoluted, however.

More generally, I'd appreciate any references to helpful literature on the subject of application error handling with streams/observables. I feel like I have a pretty good grasp of the RxSwift objects and operators and how to handle the "happy path" situation, but it's just not clear to me how to robustly handle errors in the context of continuously running application.

My solution for this is to wrap them to this type Result<AnyObject,ErrorType>

For example, user login scenario

// where API.login() takes the response data and try to map to JSON
// then try to map into Result<JSON,ErrorType>
let loginStream: Result<JSON,ErrorType> = loginTaps.flatMap { API.login() }
                                                   .shareReplay()

let loginResponse = loginStream.filter { $0.value != nil }.map { $0.value }
let loginError = loginStream.filter { $0.error != nil }.map { $0.error }

The stream will never be terminated, so no need to re-subscribe them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM