using System;
using System.Collections.Generic;

namespace WPRx1
{
    public class NumberObserver : IObservable<int>
    {
        private List<IObserver<int>> observers;

        public NumberObserver()
        {
            observers = new List<IObserver<int>>();
        }

        public IDisposable Subscribe(IObserver<int> observer)
        {
            if (!observers.Contains(observer))
                observers.Add(observer);
            return new Unsubscriber(observers, observer);

        }

        public void AddNumber(int value)
        {
            foreach (var observer in observers)
            {
                observer.OnNext(value);
            }
        }


        private class Unsubscriber : IDisposable
        {
            private List<IObserver<int>> _observers;
            private IObserver<int> _observer;

            public Unsubscriber(List<IObserver<int>> observers, IObserver<int> observer)
            {
                this._observers = observers;
                this._observer = observer;
            }

            public void Dispose()
            {
                if (_observer != null && _observers.Contains(_observer))
                    _observers.Remove(_observer);
            }
        }
    }
}
