// 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.
namespace System.Reactive
{
///
/// Class to create an instance from delegate-based implementations of the On* methods.
///
/// The type of the elements in the sequence.
public sealed class AnonymousObserver : ObserverBase
{
private readonly Action _onNext;
private readonly Action _onError;
private readonly Action _onCompleted;
///
/// Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
///
/// Observer's OnNext action implementation.
/// Observer's OnError action implementation.
/// Observer's OnCompleted action implementation.
/// or or is null.
public AnonymousObserver(Action onNext, Action onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException(nameof(onNext));
if (onError == null)
throw new ArgumentNullException(nameof(onError));
if (onCompleted == null)
throw new ArgumentNullException(nameof(onCompleted));
_onNext = onNext;
_onError = onError;
_onCompleted = onCompleted;
}
///
/// Creates an observer from the specified OnNext action.
///
/// Observer's OnNext action implementation.
/// is null.
public AnonymousObserver(Action onNext)
: this(onNext, Stubs.Throw, Stubs.Nop)
{
}
///
/// Creates an observer from the specified OnNext and OnError actions.
///
/// Observer's OnNext action implementation.
/// Observer's OnError action implementation.
/// or is null.
public AnonymousObserver(Action onNext, Action onError)
: this(onNext, onError, Stubs.Nop)
{
}
///
/// Creates an observer from the specified OnNext and OnCompleted actions.
///
/// Observer's OnNext action implementation.
/// Observer's OnCompleted action implementation.
/// or is null.
public AnonymousObserver(Action onNext, Action onCompleted)
: this(onNext, Stubs.Throw, onCompleted)
{
}
///
/// Calls the onNext action.
///
/// Next element in the sequence.
protected override void OnNextCore(T value)
{
_onNext(value);
}
///
/// Calls the onError action.
///
/// The error that has occurred.
protected override void OnErrorCore(Exception error)
{
_onError(error);
}
///
/// Calls the onCompleted action.
///
protected override void OnCompletedCore()
{
_onCompleted();
}
internal IObserver MakeSafe(IDisposable disposable)
{
return new AnonymousSafeObserver(_onNext, _onError, _onCompleted, disposable);
}
}
}