// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; namespace System.Reactive.Linq { public partial class AsyncObservable { public static IAsyncObservable FirstAsync(this IAsyncObservable source) => First(source); public static IAsyncObservable FirstAsync(this IAsyncObservable source, Func predicate) => First(source, predicate); public static IAsyncObservable FirstAsync(this IAsyncObservable source, Func> predicate) => First(source, predicate); public static IAsyncObservable First(this IAsyncObservable source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Create(source, static (source, observer) => source.SubscribeSafeAsync(AsyncObserver.First(observer))); } public static IAsyncObservable First(this IAsyncObservable source, Func predicate) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Create( source, predicate, static (source, predicate, observer) => source.SubscribeSafeAsync(AsyncObserver.First(observer, predicate))); } public static IAsyncObservable First(this IAsyncObservable source, Func> predicate) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Create( source, predicate, static (source, predicate, observer) => source.SubscribeSafeAsync(AsyncObserver.First(observer, predicate))); } } public partial class AsyncObserver { public static IAsyncObserver First(IAsyncObserver observer) { if (observer == null) throw new ArgumentNullException(nameof(observer)); return Create( async x => { await observer.OnNextAsync(x).ConfigureAwait(false); await observer.OnCompletedAsync().ConfigureAwait(false); }, observer.OnErrorAsync, async () => { await observer.OnErrorAsync(new InvalidOperationException("The sequence is empty.")).ConfigureAwait(false); } ); } public static IAsyncObserver First(IAsyncObserver observer, Func predicate) { if (observer == null) throw new ArgumentNullException(nameof(observer)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Where(First(observer), predicate); } public static IAsyncObserver First(IAsyncObserver observer, Func> predicate) { if (observer == null) throw new ArgumentNullException(nameof(observer)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Where(First(observer), predicate); } } }