RxSwift Mapping问题

时间:2017-09-19 16:05:04

标签: swift rx-swift moya

我正在使用RxSwift和Moya。我正在

  

致命错误:在解包可选值时意外发现nil

tableViewController中第authors.map {...行的

错误。当我打印authors时,我发现它是零。我无法找到问题所在。我正在使用Moya-ObjectMapper / RxSwift库。在最新版本中,Observable + Objectmapper.swift文件丢失,所以我在github上找到它并替换它。

//import libraries

class AuthorsTableViewController: UITableViewController {

    var viewModel: AuthorsViewModelType!
    var authors: Driver<RequestResult<[Author]>>!
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpBindings()
    }

    func setUpBindings() {

        tableView.dataSource = nil
        tableView.delegate = nil

        authors.map { result -> [Author] in ---> Here
            ...
            }.disposed(by: disposeBag)  
    }
}

我的ViewModel:

//import libraries

public protocol AuthorsViewModelType {
    func getAuthors(destination: YazarAPI) -> Driver<RequestResult<[Author]>>
}

public class AuthorsViewModel: AuthorsViewModelType {
    fileprivate var provider = YazarAPI.sharedProviderInstance

    public func getAuthors(destination: YazarAPI) -> Driver<RequestResult<[Author]>> {
        return provider.request(destination)
            .observeOn(MainScheduler.instance)
            .filterSuccessfulStatusCodes()
            .mapAuthors(destination: destination)
            .map { .Success($0) }
            .asDriver(onErrorRecover: { error in
                return .just(.Error(ReqestError(description: error.localizedDescription, code: .requestError)))
            })
    }
}

private extension Observable where E == Response {
    func mapAuthors(destination: YazarAPI) -> Observable<[Author]> {
        let authors: Observable<[Author]>

        switch destination {
        case .authors:
            authors = self.mapObject(Authors.self).map { $0.authors ?? [] }
        default:
            fatalError("Unexpected request type \"\(destination)\"")
        } 
        return authors
    }
}

1 个答案:

答案 0 :(得分:0)

您应该为viewModel和authors属性赋值,或者如果您将它们分配给某处,也可以在那里移动setupBindings()。 P.S。:这不是RxSwift问题