Innovenergy_trunk/csharp/app/VenusLogger/ObservableExtensions.cs

46 lines
1.2 KiB
C#

using System.Reactive.Linq;
namespace InnovEnergy.VenusLogger;
internal static class ObservableExtensions
{
public static IObservable<R> TrySelect<T, R>(this IObservable<T> source, Func<T, R> map) where R : notnull
{
return source
.Select(e => Try(map, e))
.OfType<R>();
}
public static IEnumerable<R> TrySelect<T, R>(this IEnumerable<T> source, Func<T, R> map) where R : notnull
{
return source
.Select(e => Try(map, e))
.OfType<R>();
}
public static IObservable<R> TrySelect<T, R>(this IObservable<T> source, Func<T, R> map, R onError) where R : notnull
{
return source
.Select(e => Try(map, e))
.Select(e => e is R r ? r : onError);
}
public static IEnumerable<R> TrySelect<T, R>(this IEnumerable<T> source, Func<T, R> map, R onError) where R : notnull
{
return source
.Select(e => Try(map, e))
.Select(e=>e is R r ? r : onError);
}
private static Object Try<T, R>(Func<T, R> map, T e) where R : notnull
{
try
{
return map(e);
}
catch (Exception ex)
{
return ex;
}
}
}