using System;
using System.Threading;

namespace System.Reactive
{
	internal sealed class AnonymousSafeObserver<T> : SafeObserver<T>
	{
		public AnonymousSafeObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted)
		{
			this._onNext = onNext;
			this._onError = onError;
			this._onCompleted = onCompleted;
		}

		public override void OnNext(T value)
		{
			if (this._isStopped == 0)
			{
				bool flag = false;
				try
				{
					this._onNext(value);
					flag = true;
				}
				finally
				{
					if (!flag)
					{
						base.Dispose();
					}
				}
			}
		}

		public override void OnError(Exception error)
		{
			if (Interlocked.Exchange(ref this._isStopped, 1) == 0)
			{
				try
				{
					this._onError(error);
				}
				finally
				{
					if (this != null)
					{
						((IDisposable)this).Dispose();
					}
				}
			}
		}

		public override void OnCompleted()
		{
			if (Interlocked.Exchange(ref this._isStopped, 1) == 0)
			{
				try
				{
					this._onCompleted();
				}
				finally
				{
					if (this != null)
					{
						((IDisposable)this).Dispose();
					}
				}
			}
		}

		private readonly Action<T> _onNext;

		private readonly Action<Exception> _onError;

		private readonly Action _onCompleted;

		private int _isStopped;
	}
}
