我正试图将我的API SignalProducers转换为enum,以便我获得加载,失败和加载状态。枚举是:
enum DataLoadState<DataType>{
case Loading
case Failed
case Loaded(DataType)
}
为此,我将SignalProducer转换为NoError producer,并开始加载状态:
extension SignalProducerType{
func materializeToLoadState() -> SignalProducer<DataLoadState<Value>,NoError>{
let producer = self
.map(DataLoadState.Loaded)
.startWithValue(DataLoadState.Loading)
return producer.ignoreErrors(replacementValue:DataLoadState<Value>.Failed)
}
}
extension SignalProducerType {
func startWithValue(value:Value)->SignalProducer<Value,Error>{
return SignalProducer(value:value).concat(self.producer)
}
public func ignoreErrors(replacementValue replacementValue: Self.Value? = nil) -> SignalProducer<Self.Value, NoError> {
return self.flatMapError { error in
return replacementValue.map(SignalProducer.init) ?? .empty
}
}
}
它可以工作,但我不想忽略错误,相反,我想在失败的情况下包含它:
enum DataLoadState<DataType>{
case Loading
case Failed(APIError?)
case Loaded(DataType)
}
关于我如何使用flatMapError(如在ignoreError),所以错误被触发为DataLoadState.Failed(错误)而不是被忽略的想法吗?当error不是display error时,它可以是nil。这可能吗?
修改为:
producer.flatMapError { error in SignalProducer(value:.Failed(error as? APIError)) }