我的webservice类中有以下功能:
func loadTransport() -> Observable<[TransportResponse]> {
let nonce = "\(Date().timeIntervalSince1970)"
let csaKey = try! config.apikey()
let csaSecret = try! config.apiSecret()
let csaSignature = crypto.generateSignature(nonce: nonce, url: "http://*****/v1/nmbs", body: "", secret: csaSecret)
print("SIGNATURE = \(csaSignature)")
let endpointClosure = { (target: TransportService) -> Endpoint<TransportService> in
let url = target.baseURL.appendingPathComponent(target.path).absoluteString
let endpoint = Endpoint<TransportService>(URL: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
return endpoint.adding(newHttpHeaderFields: ["CSA-KEY": csaKey,"CSA-NONCE": nonce,"CSA-SIGNATURE": csaSignature])
}
let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
return provider
.request(TransportService.nmbs)
.filterSuccessfulStatusCodes()
.mapArray(type: TransportResponse.self)
}
在我的TransportViewModel中,我有这个init方法:
init(webService: Webservice) {
self.webService = webService
title.value = String.localizedString(key: "transport_title")
transportResponse = active.asObservable()
.filter { $0 }
.flatMap { _ in
return webService.loadTransport()
}
.map { response in
return [TransportData(items: response)]
}
}
问题出在我的flatMap
方法中,但它永远不会出现在map
下面的flatMap
内。
当我将订阅部分添加到我的webservice函数时,如下所示:
let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
provider
.request(TransportService.nmbs)
.filterSuccessfulStatusCodes()
.mapArray(type: TransportResponse.self)
.subscribe { event in
switch event {
case .next(let response):
print(response)
case .error(let error):
print(error)
default: break
}
}.addDisposableTo(disposeBag)
我看到我的回复是正确打印的。 有人可以帮我吗?
答案 0 :(得分:3)
问题是,只要loadTransport()
方法完成,您的提供程序就会被释放。
您使用的是旧版Moya。在此pull request RxMoyaProvider
被弱捕获之前,整个链根本不会发出任何事件(下一个/错误/已完成)。
要修复此问题,请将提供者隐蔽到类范围的变量:
class Webservice {
var provider: RxMoyaProvider<TransportService>?
}
并像这样使用它:
self.provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
return self.provider!
.request(TransportService.nmbs)
.filterSuccessfulStatusCodes()
.mapArray(type: TransportResponse.self)