// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Reactive.Disposables; using System.Threading.Tasks; namespace System.Reactive.Linq { public static partial class AsyncObservable { public static IAsyncObservable Create(Func, Task> subscribeAsync) { if (subscribeAsync == null) throw new ArgumentNullException(nameof(subscribeAsync)); return new AnonymousAsyncObservable(subscribeAsync); } public static Task SubscribeSafeAsync(this IAsyncObservable source, IAsyncObserver observer) { if (source == null) throw new ArgumentNullException(nameof(source)); if (observer == null) throw new ArgumentNullException(nameof(observer)); return CoreAsync(); async Task CoreAsync() { try { return await source.SubscribeAsync(observer); } catch (Exception ex) { await observer.OnErrorAsync(ex).ConfigureAwait(false); return AsyncDisposable.Nop; } } } private sealed class AnonymousAsyncObservable : AsyncObservableBase { private readonly Func, Task> _subscribeAsync; public AnonymousAsyncObservable(Func, Task> subscribeAsync) { _subscribeAsync = subscribeAsync; } protected override Task SubscribeAsyncCore(IAsyncObserver observer) => _subscribeAsync(observer); } } }