我正在尝试学习 ReactiveSwift 和 ReactiveCocoa。我可以很好地使用Signal
,Property
但我遇到了麻烦SignalProducer
。
据我了解,它SignalProducer
非常适合网络请求之类的事情。我设置了我的 API 层来创建并返回一个信号提供者,调用者可以启动它。
class ApiLayer {
func prepareRequest(withInfo info: RequestInfo) -> SignalProducer<ModelType, ErrorType> {
return SignalProducer<ModelType, ErrorType> { (observer, lifetime) in
// Send API Request ...
// In Completion Handler:
let result = parseJson(json)
observer.send(value: result)
observer.sendCompleted()
}
}
}
但是我应该怎么听结果呢?
我已经尝试过这样的事情,但我得到了一个错误,所以我必须做/考虑这个错误。
apiLayer.prepareRequest(withInfo: info)
.startWithValues { (resultModel) in
// Do Stuff with result ...
}
这是我得到的错误:
对成员“startWithValues”的模糊引用
- 找到了这个候选人 (ReactiveSwift.SignalProducer< Value, NoError >)
- 找到了这个候选人(ReactiveSwift.SignalProducer< Never, NoError >)
编辑
我尝试更明确地帮助编译器识别正确的方法,就像这样。但错误仍然存在。
apiLayer.prepareRequest(withInfo: info)
.startWithValues { (resultModel: ModelType) in // Tried adding type. Error remained.
// Do Stuff with result ...
}
编辑 2
在 GitHub 支持页面获得帮助并考虑此处提供的答案后,这就是我最终得到的结果。
与我之前尝试的一个关键区别是调用者不会手动启动返回的SignalProducer
. 相反,通过在内部/响应另一个信号创建它,它隐式地在链内部开始。
我之前(错误地)假设有必要提取并明确订阅Signal
“SignalProducer
生产”的内容。
相反,我现在将SignalProducer
s 简单地视为响应刺激而启动的延迟工作。我可以手动订阅,SignalProvider
或者我可以让另一个Signal
提供该刺激。(后者在我下面更新的示例中使用。它看起来相当干净,并且比手动启动它更具 FRP 风格,这是我从我的命令式思维方式中继承下来的。)
enum ErrorType: Error {
case network
case parse
}
class ApiLayer {
func prepareRequest(withInfo info: RequestInfo) -> SignalProducer<ModelType, ErrorType> {
let producer = SignalProducer<ResultType, NoError> { (observer, lifetime) in
sendRequest(withInfo: info) { result in
observer.send(value: result)
observer.sendCompleted()
}
}
return producer
.attemptMap { result throws -> ResultType in
let networkError: Bool = checkResult(result)
if (networkError) {
throw ErrorType.network
}
}
.retry(upTo: 2)
.attemptMap { result throws -> ModelType in
// Convert result
guard let model: ModelType = convertResult(result) else {
throw ErrorType.parse
}
return model
}
// Swift infers AnyError as some kind of error wrapper.
// I don't fully understand this part yet, but to match the method's type signature, I needed to map it.
.mapError { $0.error as! ErrorType}
}
}
// In other class/method
// let apiLayer = ApiLayer(with: ...)
// let infoSignal: Signal<RequestInfo, NoError> = ...
infoSignal
.flatMap(.latest) { (info) in
apiLayer.prepareRequest(withInfo: info)
}
.flatMapError { error -> SignalProducer<ModelType, NoError> in
// Handle error
// As suggested by the ReactiveSwift documentation,
// return empty SignalProducer to map/remove the error type
return SignalProducer<ModelType, NoError>.empty
}
.observeValues { model in
// Do stuff with result ...
}