public static ITry <T> Where <T>(this ITry <T> value, Func <T, bool> evaluator, Func <Unit, Exception> error) { return(value.FlatMap(v => evaluator(v).ToTry( t => v, f => error(Unit.Value) ))); }
public static ITry <T, INonEmptyEnumerable <E> > Where <T, E>(this ITry <T, INonEmptyEnumerable <E> > value, Func <T, bool> evaluator, Func <Unit, E> error) { return(value.FlatMap(v => evaluator(v).ToTry( t => v, f => error(Unit.Value).ToEnumerable() ))); }
/// <summary> /// If the successful result passes the predicate, returns the original try. Otherwise returns erroneous try with the specified result. /// </summary> public static ITry <A, E> Where <A, E>(this ITry <A, E> t, Func <A, bool> predicate, Func <Unit, E> otherwise) { return(t.FlatMap(a => predicate(a).Match( _ => t, _ => Try.Error <A, E>(otherwise(Unit.Value)) ))); }
/// <summary> /// If the successful result passes the predicate, returns the original try. Otherwise returns erroneous try with the specified result. /// </summary> public static ITry <A, IEnumerable <E> > Where <A, E>(this ITry <A, IEnumerable <E> > t, Func <A, bool> predicate, Func <Unit, E> otherwise) { return(t.FlatMap(a => predicate(a).Match( _ => t, _ => Try.Error <A, IEnumerable <E> >(new[] { otherwise(Unit.Value) }) ))); }
private void HandlingNestedTriesWithFlatMap() { ITry <int, NetworkOperationError> number = Api.GetNumber(); ITry <ITry <int, NetworkOperationError>, NetworkOperationError> doubleNumber = number.Map(r => Api.DoubleNumber(r)); // This try succeeds only if both tries succeed. However the second lambda is only executed in case the first try is successful. ITry <int, NetworkOperationError> doubleNumberFlattened = number.FlatMap(r => Api.DoubleNumber(r)); }