title: How to get the count of items in an observable stream without maintaining state yourself?
body: <p>How do I get the number of students in this school at any given point in time using the Rx idiom and without having to maintain state in the <code>School</code> class myself?</p>
  
  <pre><code>using System;
  using System.Reactive.Subjects;
  
  namespace SchoolManagementSystem
  {
      public class School
      {
          private ISubject&lt;Student&gt; _subject = null;
          private int _maxNumberOfSeats;
          private int _numberOfStudentsAdmitted;
  
          public string Name { get; set; }
  
          public School(string name, int maxNumberOfSeats)
          {
              Name = name;
  
              _maxNumberOfSeats = maxNumberOfSeats;
  
              _numberOfStudentsAdmitted = 0;
  
              _subject = new ReplaySubject&lt;Student&gt;();
          }
  
          public void AdmitStudent(Student student)
          {
              try
              {
                  if (student == null)
                      throw new ArgumentNullException("student");
  
                  if (_numberOfStudentsAdmitted == _maxNumberOfSeats)
                  {
                      _subject.OnCompleted();
                  }
  
                  // Obviously can't do this because this will
                  // create a kind of dead lock in that it will
                  // wait for the _subject to complete, but I am 
                  // using the same _subject to issue notifications.
  
                  // _numberOfStudentsAdmitted = _subject.Count().Wait();
  
  
                  // OR to keep track of state myself
                  Interlocked.Increment(ref _numberOfStudentsAdmitted);
  
                  _subject?.OnNext(student);
              }
              catch(Exception ex)
              {
                  _subject.OnError(ex);
              }
          }
  
          public IObservable&lt;Student&gt; Students
          {
              get
              {
                  return _subject;
              }
          }
      }
  }
  </code></pre>
  
  <p>Or is this just not in tandem with the principles of components designed using Rx?</p>
  
  <p>Is this something that should be the responsibility of the client (to get the count and do all side-effects in the <code>onNext</code> handler)? And that the observables should simply act as stateless signal-sources or gates much like the hardware interrupt routines that simply signal to the CPU that something of interest has happened?</p>
  
  <p>In that case, we lose the criteria for the observable to signal completion. How then it is supposed to know when to complete?</p>