ios - RxSwift 中的 RAC tryMap 替代方案

标签 ios swift reactive-cocoa rx-swift

在 RxSwift 中实现类似 RAC tryMap 功能的推荐方法是什么?

以下代码是我如何将 json 对象映射到内部响应包装类。如果响应不符合某些条件,将返回nil,这将变成一个错误事件(tryMap实现)。

extension RACSignal{
    
    func mapToAPIResponse() -> RACSignal{
        return tryMap({ (object) -> AnyObject! in
            if let data = object as? [String:AnyObject]{
                //Some Logic
                return data["key"]
            }
            return nil
        })
    }
}

这应该如何在 RxSwift 中实现?

更新的可能解决方案

我为 Rx-Swift 提出了以下解决方案。开放寻求更好的解决方案。

extension Observable{
    
    func mapToAPIResponse() -> Observable<APIResponse>{
        return map({ (object) in
            
            guard let dictionary = object as? [String:AnyObject] else{
                //APIResponseError.InvalidResponseFormat is defined in other class.
                throw APIResponseError.InvalidResponseFormat
            }
           
            
            let response = APIResponse()

            //Complete API Response
            return response

        })
}

我的结论是在映射内使用 throw 来处理错误。

最佳答案

您的解决方案是正确的,这就是为什么 RxSwift 中的 map 运算符使用 throws 进行注释。 Release notes of RxSwift 2明确说明这一点:

Adds support for Swift 2.0 error handling try/do/catch.

You can now just write

API.fetchData(URL)
  .map { rawData in
      if invalidData(rawData) {
          throw myParsingError
      }

      ...

      return parsedData
  }

即使在`RxCocoa

关于ios - RxSwift 中的 RAC tryMap 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36554154/

相关文章:

ios - 未通过 updateViewConstraints 添加约束

ios - 无法将类型 'NSDictionary' 的值转换为指定类型 'Dictionary'

ios - 无法将 String 类型的值分配给 AnyObject 类型? swift 3.0

ios - 在 View Controller 之间传递数据时出错

ios - RACObserve(), RAC() - 如何根据 NSString 设置 BOOL 值

ios - rac_signalForSelector : needs empty implementation

ios - 如何在公共(public)级别控制 Parse ACL

ios - 等到多个网络请求都执行完毕——包括它们的完成 block

swift - 如何以编程方式显示 NSTextView 的查找面板?

ios - ReactiveCocoa 结合最新的按钮按下和文本字段委托(delegate)信号