我正在尝试将我的API SignalProducers转换为枚举,因此我得到了Loading,Failed和Loaded状态。 Enum是:
public static class EntityExtensions
{
public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> query,
Expression<Func<T,TProperty>> include) where T : class
{
TestDB.Includes.Add(include);
var method = typeof(QueryableExtensions)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Where(m => m.Name == "Include")
.First(m => m.GetParameters().All(p => p.ParameterType.IsGenericType));
var generic = method.MakeGenericMethod(typeof(T), typeof(TProperty));
return (IQueryable<T>)generic.Invoke(query, new object[] { query, include });
}
}
为此,我将SignalProducer转换为NoError生成器并以加载状态开始:
enum DataLoadState<DataType>{
case Loading
case Failed
case Loaded(DataType)
}
它有效,但我不想忽略错误,而是想把它包含在失败的情况中:
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
}
}
}
我对如何使用flatMapError(如ignoreError)有任何想法,因此错误会被触发为DataLoadState.Failed(错误)而不是被忽略?当错误不显示时,错误可能只是零。它甚至可能吗?
答案 0 :(得分:0)
好的,只需修改:
producer.flatMapError { error in SignalProducer(value:.Failed(error as? APIError)) }