<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Richard&#039;s Random Ramblings &#187; Rx</title>
	<atom:link href="http://blog.rjcox.co.uk/category/dev/rx/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.rjcox.co.uk</link>
	<description>Whatever I think is interesting... mostly about computing but not always</description>
	<lastBuildDate>Tue, 22 Jun 2010 13:29:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating a Reusable “ObservableSource” for the Reactive Extensions (part 6.1)</title>
		<link>http://blog.rjcox.co.uk/2010/03/18/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-6-1/</link>
		<comments>http://blog.rjcox.co.uk/2010/03/18/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-6-1/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 17:09:26 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=122</guid>
		<description><![CDATA[Preparing For Implementing Concurrency

Introduction

  The next step in this series on creating my own
  IObservable&#60;T&#62; implementation is concurrency.
  (See below for links to previous parts,
  Part 5
  has a full code listing.)


  This is the hard part. Too easy to think it is OK when it isn&#8217;t, and
  [...]]]></description>
			<content:encoded><![CDATA[<h2>Preparing For Implementing Concurrency</h2>

<h3>Introduction</h3>
<p>
  The next step in this series on creating my own
  <code>IObservable&lt;T&gt;</code> implementation is concurrency.
  (See <a href='#previously'>below</a> for links to previous parts,
  <a href="/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-5/">Part 5</a>
  has a full code listing.)
</p>
<p>
  This is the hard part. Too easy to think it is OK when it isn&rsquo;t, and
  too hard to validate that is really thread safe.
</p>
<p>
  The only option is careful analysis, and then double (triple, &hellip;) check
  everything.
<p>
<p>
  After all even the best set of unit tests will fail to find problems if
  it takes a particular combination of OS version, hardware and other
  processes running to show the problem. With race conditions, deadlocks
  and all the other concurrency <em>fun</em> such is not just a possibility
  but likely.
</p>
<p>
  But first, the new 1.0.2350.0 (2010-03-15) build of Rx makes
  no change to my code, all tests pass without any changes. And this
  is now running on my main system (Rx has go-live licence, so why not)
  with its multiple codes (previously was working on a VM with a single
  virtual CPU).
</p>

<h3>What Needs Protection?</h3>
<p>
  At the heart of my implementation there is some shared data. This needs
  protecting where multiple threads could operate concurrently. E.g. while
  events are pushed to subscribers using a copy of the list of subscribers
  (this allows re-entrant subscription and un-subscription) taking a copy of
  the values of a <code>Dictionary&lt;K,V&gt;</code> certainly is not
  safe.
</p>
<p>
  Some operations are inherently safe (defined by the platforms object model,
  see <a href='http://www.bluebytesoftware.com/blog/'>Joe Duffy&rsquo;s blog</a>
  for more details). In this case reading or writing an aligned, volatile
  <code>int</code> or reference is safe (such reads and writes are inherently
  atomic). And only a single field needs to be checked, written to, or both
  compared &amp; exchanged (via <code>Interlocked.CompareExchange</code>):
</p>
<ul>
  <li>
    <p>
      Checking if the <code>endOfEvents</code> field (reference to a
      <code>Notification&lt;T&gt;</code>) is <code>null</code>.
    </p>
  </li>
  <li>
    <p>
      The boolean field <code>pushingEvents</code> used only in <code>PushEvents</code>
      (the method that loops through a snapshot of the current subscribers) to avoid
      re-entrant or multi-threaded pushing of events.
    </p>
    <p>
      When it is read, and true in a simple check there is no problem
      (just return from <code>PushEvents</code>. But if it is false it then
      needs to be set. So two operations are needed: a read and a write.
      <code>Interlocked.CompareExchange</code> will take care of this without
      a lock. (Before returning from pushing events it is set back to false,
      but a single write is also OK.)
    </p>
    <p>
      As there is no overload of <code>Interlocked.CompareExchange</code> for
      <code>bool</code> the field will need to be an <code>int</code> with
      values 0 and 1.
    </p>
  </li>
  <li>
    <p>
      To avoid races in <code>Next</code>, <code>Completed</code>
      and <code>Error</code> between checking for <code>endOfEvents</code>
      and setting it one can use <code>Interlocked.CompareExchange</code>.
    </p>
  </li>
</ul>
<p>
  There are also two pieces of functionality that require multiple operations
  on fields (or objects that are not thread safe). In each case a lock is needed.
</p>
<ul>
  <li>
    <p>
      The collection of subscribers and subscriber id counter. With operations
      to add or remove a subscriber, and to snapshot a list of all subscribers.
      This will require a lock, there is no way (I can see) around this.
    </p>
  </li>
  <li>
    <p>
      To operate on the queue of pending events can be handled by changing to
      an instance of <code>ConcurrentQueue&lt;T&gt;</code> with modifications
      in <code>PushEvents</code> to use <code>TryDequeue</code> rather than a
      combination of checking the count and then <code>Dequeue</code>.
    </p>
  </li>
</ul>

<h4>What Doesn&rsquo;t Need Protection</h4>
<p>
  This implementation is not about being fair. So if two threads
  both try and use an instance together, with one calling
  <code>Next</code> and the other <code>Completed</code> only
  the Windows thread scheduler gets any say in which wins (if
  <code>Completed</code> is called first, no subscriber will see
  the value passed to <code>Next</code>).
</p>

<h3>Ready to Implement?</h3>
<p>
  Even as I wrote the analysis above (which was already the second pass through
  what would be needed) I noted that I could avoid a lock for <code>Next</code>,
  <code>Completed</code>, and <code>Error</code> and use <code>CompareExchange</code>.
  So I&rsquo;ve probably still missed something: time for another pass over the code.
</p>
<p>
  And another question is how to test&hellip;? Throwing a load of cocurrent tasks
  from the Parallel Extensions (see <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx">here</a>)
  will be a start, but cannot really cover mixing in <code>Completed</code> and
  <code>Error</code> because I cannot determine which thread will win and which
  will not, and thus no way to verify the &ldquo;right one&rdquo; won in a unit
  test assert.
</p>
<p>
  More to work on.
</p>

<h3><a id='previously'></a>Previously</h3>
<ul>
  <li>
    <p>
      <a href="/2010/01/22/observable-implementation-1/">Part 1</a>: The
      basic implementation of </code>Subscribe</code>, unsubscribe and
      </code>Next</code>.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/01/24/observable-implementation-2/">Part 2</a>: Making
      </code>Subscribe</code> and unsubscribe re-entrant.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/02/04/observable-implementation-3/">Part 3</a>: Why
      re-entrancy is important.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/02/17/observable-implementation-4/">Part 4</a>: Making
      <code>Next</code> re-entrant.
    </p>
  </li>
  <li>
    <p>
      <a href="/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-5/">Part 5</a>:
      Implementing <code>OnCompleted</code> and <code>OnError</code> to complete
      support for full <code>IObserver&lt;T&gt;</code> interface.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/03/09/observable-implementation-5a/">Part 5a</a>: Updates
      for build 1.0.2317.0 of the Reactive Extensions (2010-03-05).
    </p>
  </li>

</ul>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/03/18/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-6-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable “ObservableSource” for the Reactive Extensions (part 5a)</title>
		<link>http://blog.rjcox.co.uk/2010/03/09/observable-implementation-5a/</link>
		<comments>http://blog.rjcox.co.uk/2010/03/09/observable-implementation-5a/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 15:43:37 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=119</guid>
		<description><![CDATA[Updates for Next Reactive Extensions (Rx) Code Drop


  The new code drop came through, 2&#189; months after the last drop, on 5th March. The
  release notes
  are suitably long. With a fair amount of change, much of it under the covers to edge cases.


  But a fair number of things have [...]]]></description>
			<content:encoded><![CDATA[<h3>Updates for Next Reactive Extensions (Rx) Code Drop</h3>

<p>
  The new code drop came through, 2&frac12; months after the last drop, on 5<sup>th</sup> March. The
  <a href="http://blogs.msdn.com/rxteam/archive/2010/03/05/release-notes.aspx">release notes</a>
  are suitably long. With a fair amount of change, much of it under the covers to edge cases.
</p>
<p>
  But a fair number of things have moved assemblies and changed name.
</p>

<h4>Impact on My Implementation</h4>
<p>
  Given all the change, there was relatively little impact. The only thing that broke was
  my use of <code>Notification&lt;T&gt;</code>: the <code>Current</code>
  property is now called <code>Value</code>. And it now has an <code>Exception</code>
  property, which saves a cast when handling an OnError notification.
</p>
<p>
  My (unpublished) test harness used <code>GroupDisposable</code> to clean up
  subscriptions, this was renamed <code>CompositeDisposable</code> and moved to
  the CoreEx assembly.
</p>
<p>
  Both of these renames give slightly better and more consistent names, and the addition
  of the <code>Exception</code> property is definitely better. So overall the new drop is,
  for me, an improvement so far: once the code compiled all tests just passed.
</p>
<p>
  The only function that changed was <code>SendNotification</code> so following DRY helped.
  The new implementation:
</p>
<pre>private static void SendNotification(IObserver&lt;T&gt; obs, Notification&lt;T&gt; n) {
    switch (n.Kind) {
    case NotificationKind.OnNext:
        Debug.Assert(n.HasValue);
        obs.OnNext(n.Value);
        break;
    case NotificationKind.OnCompleted:
        obs.OnCompleted();
        break;
    case NotificationKind.OnError:
        obs.OnError(n.Exception);
        break;
    }
}</pre>

<h4>So Where&rsquo;s The Concurrency Support&hellip;?</h4>
<p>
  Coming! :-)<br/>
  I've been rather head down in learning WPF for something else, and trying to avoid 
  too many distractions while getting my head around the basics of WPF. Concurrency
  support is perhaps the biggest challenge here and I therefore want to be able to focus
  on it and get it right. This will mean taking a block of focused time.
</p>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/03/09/observable-implementation-5a/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable “ObservableSource” for the Reactive Extensions (part 5)</title>
		<link>http://blog.rjcox.co.uk/2010/02/24/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-5/</link>
		<comments>http://blog.rjcox.co.uk/2010/02/24/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-5/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 15:22:02 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=111</guid>
		<description><![CDATA[Adding Completed and Error Methods

Introduction

  So far in this series (links below) the focus has been on implementing
  Next and Subscribe in a way that is re-entrant.
  But that leaves two methods uncovered. Both Completed and
  Error end the sequence, but in different ways.
  Error passes an exception indicating the [...]]]></description>
			<content:encoded><![CDATA[<h2>Adding <code>Completed</code> and <code>Error</code> Methods</h2>

<h3>Introduction</h3>
<p>
  So far in this series (links below) the focus has been on implementing
  <code>Next</code> and <code>Subscribe</code> in a way that is re-entrant.
  But that leaves two methods uncovered. Both <code>Completed</code> and
  <code>Error</code> end the sequence, but in different ways.
  <code>Error</code> passes an exception indicating the source has failed,
  whereas <code>Completed</code> just indicates it has ended.
</p>
<p>
  Based on <code>Subject&lt;T&gt;</code> when a sequence of events is ended:
</p>
<ul>
  <li>
    <p>
      Existing subscribers received a call to their <code>OnError</code>
      or <code>OnCompleted</code> (as applicable).
    </p>
  </li>
  <li>
    <p>
      Further calls to any of <code>Subject&lt;T&gt;</code>'s
      <code>IObserver&lt;T&gt;</code> methods is a no-op.
    </p>
  </li>
  <li>
    <p>
      Any new subscribers immediately get a call to their <code>OnError</code>
      or <code>OnCompleted</code> (as applicable) and nothing more.
    </p>
  </li>
</ul>

<h4>Previously</h4>
<ul>
  <li>
    <p>
      <a href="/2010/01/22/observable-implementation-1/">Part 1</a>: The
      basic implementation of </code>Subscribe</code>, unsubscribe and
      </code>Next</code>.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/01/24/observable-implementation-2/">Part 2</a>: Making
      </code>Subscribe</code> and unsubscribe re-entrant.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/02/04/observable-implementation-3/">Part 3</a>: Why
      re-entrancy is important.
    </p>
  </li>
  <li>
    <p>
      <a href="/2010/02/17/observable-implementation-4/">Part 4</a>: Making
      <code>Next</code> re-entrant.
    </p>
  </li>
</ul>

<h3><code>Notification&lt;T&gt;</code> As A Way to Store An Observable Sequence</h3>
<p>
  The reactive Framework (Rx) distributable comes with three assemblies:
</p>
<ul>
  <li><p>System.CoreEx</p></li>
  <li><p>System.Reactive</p></li>
  <li><p>System.Interactive</p></li>
</ul>
<p>
  System.CoreEx contains types that would have been in System or System.Core
  had .NET been designed with Rx in it from the start. System.Interactive
  extends LINQ to Objects by back-porting many of <code>IObservable&lt;T&gt;</code>'s
  extension methods (or &rsquo;operators&rdquo;) to <code>IEnumerable&lt;T&gt;</code>.
  System.Reactive implements LINQ like operators for <code>IObservable&lt;T&gt;</code>.
</p>
<p>
  My observable implementation almost doesn&rsquo;t need any of these
  three assemblies (<code>IObservable&lt;T&gt;</code> and <code>IObserver&lt;T&gt;</code>
  being defined in the mscorlib assembly).
</p>
<p>
  However one rather useful group of types defined in the System.CoreEx
  assembly in namespace System.Collections.Generic are <code>Notification&lt;T&gt;</code>
  and its subtypes. These types allow the &ldquo;value&rdquo; of an observable event
  to be stored. Using one of the three subtypes (one each for <code>OnNext</code>,
  <code>OnCompleted</code> and <code>OnError</code>) defined as members of
  <code>Notification&lt;T&gt;</code> (hence created as, for example,
  <code>new Notification&lt;int&gt;.OnNext(1)</code>). Therefore a collection
  of events covering all three <code>IObserver&lt;T&gt;</code> methods can be
  easily created without some custom helper types.
</p>
<p>
  These types are provided for the <code>Materialize</code> and
  <code>Dematerialise</code> enumerable and observable operators (the former being
  one the back-ported operators in System.Interactive).
</p>

<h3>Overview of The Implementation of <code>Completed</code> and <code>OnError</code></h3>
<p>
  Both follow the same pattern as the existing <code>Next</code> implementation:
</p>
<ol>
  <li><p>If ended, return</p></li>
  <li><p>Add the new event to a queue of pending events.</p></li>
  <li><p>If not already pushing an event, process the queue.</p></li>
</ol>
<p>
  The first of these steps is new, and handles the requirement that either
  <code>Completed</code> or <code>OnError</code> ends the sequence.
</p>
<p>
  To make handling new subscriptions after the end of the sequence
  the <code>endOfSequnec</code> field is a
  <code>Notification&lt;T&gt;</code> reference. If null the sequence has not
  ended, otherwise this is the event to immediately push. Also a helper
  from System.Reactive is used as the return value:
  <code>System.Disposables.Disposable.Empty</code> which is an instance of
  a type which implements <code>IDisposable</code> as a no-op and these is
  no need to track this after the end subscriber (it will never be called
  again).
</p>

<h3>The New Implementation</h3>
<p>
  The single biggest change to support storing notifications (rather than
  values of type <code>T></code>) is in <code>PushEvents</code> where
  different kinds of notifications need to call different
  <code>IObserver&lt;T&gt;</code> methods, so a switch is needed. This is
  in its own method (<code>SendNotification</code>) because it can then
  be reused to send the ending event to post-end subscribers.
</p>
<p>
  The implementations of <code>Next</code>, <code>Completed</code> and
  <code>Error</code> end up being very similar and simple.
</p>
<p>
  Overall, compared to the code from
  <a href="/2010/02/17/observable-implementation-4/">part 4</a>, the
  implementation is a somewhat longer, but certainly better factored with
  each method doing one thing. The most complex (<code>PushEvents</code>)
  does have to loop over both pending events and subscribers, but that
  is all it does.
</p>

<h3>The Code</h3>
<pre>using System;
using System.Collections.Generic;
using System.Linq;

public class Observable4&lt;T&gt; : IObservable&lt;T&gt; {
    private Dictionary&lt;int, IObserver&lt;T&gt;&gt; subscribers = new Dictionary&lt;int, IObserver&lt;T&gt;&gt;();
    private int nextSubscriber = 0;
    private Queue&lt;Notification&lt;T&gt;&gt; pendingEvents = new Queue&lt;Notification&lt;T&gt;&gt;();
    private bool pushingEvent = false;  // If true, only queue the event.
    private Notification&lt;T&gt; endOfEvents;   // Not null =&gt; have had ended, and this is the Completed or Error that ended it.

    public IDisposable Subscribe(IObserver&lt;T&gt; observer) {
        if (endOfEvents != null) {
            // Already have end of sequence, so just tell this new subscriber
            // and return no-op.
            SendNotification(observer, endOfEvents);
            return System.Disposables.Disposable.Empty;
        } else {
            subscribers.Add(nextSubscriber, observer);
            return new Observable4Disposer(this, nextSubscriber++);
        }
    }

    private void Unsubscribe(int index) {
        subscribers.Remove(index);
    }

    public void Next(T value) {
        if (endOfEvents != null) { return; }
        pendingEvents.Enqueue(new Notification&lt;T&gt;.OnNext(value));
        PushEvents();
    }

    public void Completed() {
        if (endOfEvents != null) { return; }
        endOfEvents = new Notification&lt;T&gt;.OnCompleted();
        pendingEvents.Enqueue(endOfEvents);
        PushEvents();
    }

    public void Error(Exception exn) {
        if (endOfEvents != null) { return; }
        endOfEvents = new Notification&lt;T&gt;.OnError(exn);
        pendingEvents.Enqueue(endOfEvents);
        PushEvents();
    }

    private void PushEvents() {
        if (!pushingEvent) {
            try {
                pushingEvent = true;
                while (pendingEvents.Count &gt; 0) {
                    // To allow subscribers to unsubscribe while calling them, don't
                    // directly iterate over the collection, but use a copy.
                    // Take this each time, in case some event triggers a change
                    var subs = subscribers.Values.ToArray();
                    var n = pendingEvents.Dequeue();
                    foreach (var s in subs) {
                        SendNotification(s, n);
                    }
                }
            } finally {
                pushingEvent = false;
            }
        }
    }

    private static void SendNotification(IObserver&lt;T&gt; obs, Notification&lt;T&gt; n) {
        switch (n.Kind) {
        case NotificationKind.OnNext:
            obs.OnNext(n.Current);
            break;
        case NotificationKind.OnCompleted:
            obs.OnCompleted();
            break;
        case NotificationKind.OnError:
            obs.OnError(((Notification&lt;T&gt;.OnError)(n)).Exception);
            break;
        }
    }


    private class Observable4Disposer : IDisposable {
        private Observable4&lt;T&gt; target;
        private int index;
        internal Observable4Disposer(Observable4&lt;T&gt; target, int index) {
            this.target = target;
            this.index = index;
        }

        public void Dispose() {
            target.Unsubscribe(index);
        }
    }
}</pre>

<h3>Further Steps</h3>
<p>
  The toughest part to get right is still left: concurrency. This will be
  difficult as much to test as to implement, tests using workers are never
  simple and just being confident that they are doing things concurrently
  is hard (after all a simple <code>Interlocked.Increment</code> might
  be slow enough to effectively eliminate any concurrency due to forcing
  CPU cache synchronisation even with multiple idle cores).
</p>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/02/24/creating-a-reusable-%e2%80%9cobservablesource%e2%80%9d-for-the-reactive-extensions-part-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ractive Framework’s Observer.Create Doesn&#8217;t Create a Pure Wrapper</title>
		<link>http://blog.rjcox.co.uk/2010/02/22/observer-create-has-logic/</link>
		<comments>http://blog.rjcox.co.uk/2010/02/22/observer-create-has-logic/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 11:49:04 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=106</guid>
		<description><![CDATA[What Happens When One’s Test Doesn’t Fail When It Should, or, Why
Observer.Create&#60;T&#62; Isn’t Good For Testing Observables

Introduction

  In building my own implementation of IObservable&#60;T&#62;
  across a series of posts
  (Part 1,
  Part 2,
  Part 3 and
  Part 4)
  I’ve been making heavy use of Observer.Create&#60;T&#62; to create
  [...]]]></description>
			<content:encoded><![CDATA[<h2>What Happens When One’s Test Doesn’t Fail When It Should, or, Why
<code>Observer.Create&lt;T&gt;</code> Isn’t Good For Testing Observables</h2>

<h3>Introduction</h3>
<p>
  In building my own implementation of <code>IObservable&lt;T&gt;</code>
  across a series of posts
  (<a href="/2010/01/22/observable-implementation-1/">Part 1</a>,
  <a href="/2010/01/24/observable-implementation-2/">Part 2</a>,
  <a href="/2010/02/04/observable-implementation-3/">Part 3</a> and
  <a href="/2010/02/17/observable-implementation-4/">Part 4</a>)
  I’ve been making heavy use of Observer.Create&lt;T&gt; to create
  helper observer instances to ensure that the right methods of the
  subscribed observers are called, the right number of times (and
  even&mdash;although somewhat harder to track in all but the
  simplest cases&mdash;the right order).
</p>

<h3>The Discovery</h3>
<p>
  In working towards Part 5 which will cover implementing the two,
  so far missing, methods of <code>IObserver&lt;T&gt;</code>:
  <code>OnCompleted</code> and <code>OnError</code> I was rather surprise
  when this test passed:
</p>
<pre>[TestMethod]
public void Observable4_CallingCompletedAgainIsNoOp() {
    bool hasCompleted = false;
    var sub = Obs.Create&lt;int&gt;(
        i =&gt; { Assert.Fail("OnNext should not have been called"); },
        exn =&gt; { Assert.Fail("OnError should not have been called"); },
        () =&gt; {
            Assert.IsFalse(hasCompleted, "OnCompleted for single subscriber called multiple times");
            hasCompleted = true;
        });

    var source = new Observable4&lt;int&gt;();
    using (var unsub = source.Subscribe(sub)) {
        source.Completed();
        source.Completed();
    }
    Assert.IsTrue(hasCompleted);
}</pre>
<p>
  When I knew that <code>Observable4&lt;int&gt;.Completed</code> had no
  logic to prevent <code>IObserver&lt;T&gt;.OnComplete</code> being called
  multiple times. Under the debugger it was quite clear that the
  third lambda was not being called (briefly I considered a debugger bug,
  but decided to check more fully first).
</p>
<p>
  I looked at the implementation of <code>Observer.Create&lt;T&gt;</code> in
  <a href="http://reflector.red-gate.com/">Reflector</a>. That factory method
  creates an instance of an internal type, which derives from another internal
  type <code>AbstractObserver&lt;T&gt;</code>. So far largely as expected.
</p>
<p>
  But in looking at the implementation of the <code>IObserver&lt;T&gt;</code>
  methods I saw:
</p>
<pre>public void OnCompleted() {
    if (!this.IsStopped) {
        this.IsStopped = true;
        this.Completed();
    }
}</pre>
<p>
  I.e. it keeps track of a call to <code>OnCompleted</code> and blocks
  further events. All three <code>IObserver&lt;T&gt;</code> methods check
  for <code>IsStopped</code>, and it is also set in <code>OnError</code>.
</p>

<h3>The Implication</h3>
<p>
  If I want an observer that I can use to test an observable for compliance
  to the <code>IObserver&lt;T&gt;</code> semantic contract, I cannot use
  <code>Observer.Create&lt;T&gt;</code>. It will hide breaking the
  &ldquo;<code>OnCompleted</code> or <code>OnError</code> end the
  observable&rsquo;s event sequence&rdquo;.
</p>

<h3>The Solution</h3>
<p>
  In the end the fix is rather easy: make my own
  <code>Observer.Create&lt;T&gt;</code> which doesn’t contain any such
  logic. This is rather simple:
</p>
<pre>public static class Obs {
    public static AnonObserver&lt;T&gt; Create&lt;T&gt;(Action&lt;T&gt; onNext) {
        return new AnonObserver&lt;T&gt;(onNext);
    }
    public static AnonObserver&lt;T&gt; Create&lt;T&gt;(Action&lt;T&gt; onNext, Action&lt;Exception&gt; onError, Action onComplete) {
        return new AnonObserver&lt;T&gt;(onNext, onError, onComplete);
    }
}

public class AnonObserver&lt;T&gt; : IObserver&lt;T&gt; {
    private Action&lt;T&gt; onNext;
    private Action onComplete;
    private Action&lt;Exception&gt; onError;

    public AnonObserver(Action&lt;T&gt; onNext) {
        if (onNext == null) { throw new ArgumentNullException("onNext"); }
        this.onNext = onNext;
    }
    public AnonObserver(Action&lt;T&gt; onNext, Action&lt;Exception&gt; onError, Action onComplete) {
        if (onNext == null) { throw new ArgumentNullException("onNext"); }
        if (onError == null) { throw new ArgumentNullException("onError"); }
        if (onComplete == null) { throw new ArgumentNullException("onComplete"); }
        this.onNext = onNext;
        this.onError = onError;
        this.onComplete = onComplete;
    }

    public void OnCompleted() {
        if (onComplete != null) {
            onComplete();
        }
    }

    public void OnError(Exception error) {
        if (onError != null) {
            onError(error);
        }
    }

    public void OnNext(T value) {
        onNext(value);
    }
}</pre>
<p>
  I now need to just replace all the use of <code>Observer.Create&lt;T&gt;</code>
  with <code>Obs.Create&lt;T&gt;</code> (and try and think of a better name).
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/02/22/observer-create-has-logic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable “ObservableSource” for the Reactive Extensions (part 4)</title>
		<link>http://blog.rjcox.co.uk/2010/02/17/observable-implementation-4/</link>
		<comments>http://blog.rjcox.co.uk/2010/02/17/observable-implementation-4/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 18:07:51 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=97</guid>
		<description><![CDATA[Supporting Re-entrant Event Publication: Implementation

Introduction

  In Part 3 I looked
  at the effect of calling Subject&#60;T&#62;.OnNext from within
  a subscriber to that Subject&#60;T&#62;. I really do not think
  that the out of order events that creates are going to create anything
  other than confusion.


  In my implementation, continuing on [...]]]></description>
			<content:encoded><![CDATA[<h2>Supporting Re-entrant Event Publication: Implementation</h2>

<h3>Introduction</h3>
<p>
  In <a href="/2010/02/04/observable-implementation-3/">Part 3</a> I looked
  at the effect of calling <code>Subject&lt;T&gt;.OnNext</code> from within
  a subscriber to that <code>Subject&lt;T&gt;</code>. I really do not think
  that the out of order events that creates are going to create anything
  other than confusion.
</p>
<p>
  In my implementation, continuing on from
  <a href="/2010/01/22/observable-implementation-1/">Part 1</a> and
  <a href="/2010/01/24/observable-implementation-2/">Part 2</a>, I
  want to avoid the implicit re-ordering that happens when
  <code>Next(<em>value</em>)</code> is called from within a subscriber.
</p>

<h3>The Re-Entrant Implementation</h3>
<p>
  In the basic implementation a snapshot of the subscribers is taken
  (to avoid problems with the collection being modified by re-entrant
  subscribe and unsubscribe operations), then iterated over:
<p>
<pre>var subs = subscribers.Values.ToArray();
foreach (var sub in subs) {
   sub.OnNext(value);
}</pre>
<p>
  In the case of a re-entrant <code>Next</code> call this loop will simply
  exist on the stack twice:
</p>
<pre>Observable2<int>.Next()
ATestObserver.OnNext()
Observable2<int>.Next()</pre>
<p>
  With the second call iterating through the list of subscribers before
  the first moves on to the next.
</p>
<p>
  The solution here is to recognise that an iteration is taking place already
  when <code>Next</code> is called and, rather than just looping to call all
  subscribers, buffer up the new value. The original call keeps looping
  until all buffered values are sent out. (Once, later in this series,
  concurrency is introduced locking is going to be needed here.)
</p>
<p>
  First two new fields are needed. A <code>Queue</code> to act as buffer, and
  a flag to indicate events are currently being pushed to the subscribers:
</p>
<pre>private Queue&lt;T&gt; pendingEvents = new Queue&lt;T&gt;();
private bool pushingEvent = false;</pre>
<p>
  Then reworking the <code>Next</code> implementation:
</p>
<pre>pendingEvents.Enqueue(value);
if (!pushingEvent) {
    try {
        pushingEvent = true;
        while (pendingEvents.Count &gt; 0) {
            var subs = subscribers.Values.ToArray();
            var v = pendingEvents.Dequeue();
            foreach (var s in subs) {
                s.OnNext(v);
            }
        }
    } finally {
        pushingEvent = false;
    }
}</pre>
<p>
  A few points worth noting:
</p>
<ul>
  <li>
    <p>
      By always putting the new event value in the queue there is no special
      cases needed for the first event
    </p>
  </li>
  <li>
    <p>
      The try&hellip;finally ensures the <code>pushingEvent</code> gets reset, but
      this could leave un-pushed events. This is a consequence of the RX
      exception model (propogate back to the called), but with the added
      twist that a re-entrant call to this will not get the exception, the
      original caller of <code>Next</code> will.
    </p>
  </li>
  <li>
    <p>
      I have chosen to re-snapshot the subscribers for each event. This will
      avoid a subscriber that unsubscribes in response to one event getting
      more, even if already queued up.
    </p>
  </li>
</ul>

<h3>Next Steps</h3>
<p>
  This is still missing <code>Exception</code> and <code>Complete</code>
  methods (to call <code>IObserver&lt;T&gt;.Error()</code> and
  <code>.OnCompleted</code>.
</p>
<p>
  &hellip;and concurrency support of course.
</p>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/02/17/observable-implementation-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable &#8220;ObservableSource&#8221; for the Reactive Extensions (part 3)</title>
		<link>http://blog.rjcox.co.uk/2010/02/04/observable-implementation-3/</link>
		<comments>http://blog.rjcox.co.uk/2010/02/04/observable-implementation-3/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 17:59:48 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=83</guid>
		<description><![CDATA[Supporting Re-entrant Event Publication: Why It is Significant
Introduction

  Continuing from
  Part 1
  and
  Part 2
  where the first steps to a reusable
  IObservable&#60;T&#62; were taken.


  But this is something of an aside. Because in starting to look at the reasons
  to explicitly support this, I found that [...]]]></description>
			<content:encoded><![CDATA[<h2>Supporting Re-entrant Event Publication: Why It is Significant</h2>
<h3>Introduction</h3>
<p>
  Continuing from
  <a href="/2010/01/22/oberservable-implementation-1-2/">Part 1</a>
  and
  <a href="/2010/01/24/oberservable-implementation-2/">Part 2</a>
  where the first steps to a reusable
  <code>IObservable&lt;T&gt;</code> were taken.
</p>
<p>
  But this is something of an aside. Because in starting to look at the reasons
  to explicitly support this, I found that the RX type <code>Subject&lt;T&gt;</code>
  (in assembly "System.Reactive", namespace <code>System.Collections.Generic</code>)
  has exactly the same behaviour as <code>Observable2&lt;T&gt;</code> from
  <a href="/2010/01/24/oberservable-implementation-2/">Part 2</a>.
</p>
<p>
  Personally I feel that this behaviour will lead to inconsistent and unexpected
  ordering of events as seen by subscribers, depending on the order in which
  the observers subscribed and the details of the internals of the observable
  (what kind of collection is used to store the list of subscribers). This
  opens up the potential of races to subscribe with different timing leading to
  seeing out of order events.
</p>
<p>
  One final note here, where I started drafting my implementation of
  <code>IObservable&lt;T&gt;</code> I was not aware of <code>Subject&lt;T&gt;</code>.
  When I became aware of this type, I almost decided to give up on my own implementation.
  With this discovery I am not rather glad I didn't.
</p>

<h3>The Test Code</h3>
<pre>var obs = new Subject&lt;int&gt;();
var subCalls = 0;
var sub1Calls = 0;

var sub0 = Observer.Create&lt;int&gt;(i =&gt; {
    ++subCalls;
    Console.WriteLine("Sub 0 ({2}): sub1 called {0} times (total subscriber calls {1})", sub1Calls, subCalls, i);
});
var sub1 = Observer.Create&lt;int&gt;(i =&gt; {
    ++subCalls;
    ++sub1Calls;
    Console.WriteLine("Sub 1 ({2}): sub1 called {0} times (total subscriber calls: {1})", sub1Calls, subCalls, i);
    if (i &gt; 0 && i &lt; 3) {
	obs.OnNext(-1 * i);
    }
});
var sub2 = Observer.Create&lt;int&gt;(i =&gt; {
    ++subCalls;
    Console.WriteLine("Sub 2 ({2}): sub1 called {0} times (total subscriber calls: {1})", sub1Calls, subCalls, i);
});

using (var d0 = obs.Subscribe(sub0))
using (var d1 = obs.Subscribe(sub1))
using (var d2 = obs.Subscribe(sub2)) {
    obs.OnNext(1);
}

Console.WriteLine("END: sub1 called {0} times, all subscribers {1} times", sub1Calls, subCalls);</pre>
<p>
  In this the three subscribers (imaginatively named <code>sub0</code>, <code>sub1</code>
  and <code>sub2</code>) all increment a count of subscriber calls, and all
  print the same details to the console: which subscriber, the event value, the
  total number of subscriber calls and the number of calls to the second subscriber
  (<code>sub1</code).
</p>
<p>
  Additionally the second subscriber will raise an event itself,
  recursively publishing an event if the current value is
  1&le;<i>i</i>&le;2 with value -1&times;<i>i</i>. Thus there is no more
  than a single level of recursion.
</p>
<h3>The Results</h3>
<pre>Sub 0 (1): sub1 called 0 times (total subscriber calls 1)
Sub 1 (1): sub1 called 1 times (total subscriber calls: 2)
Sub 0 (-1): sub1 called 1 times (total subscriber calls 3)
Sub 1 (-1): sub1 called 2 times (total subscriber calls: 4)
Sub 2 (-1): sub1 called 2 times (total subscriber calls: 5)
Sub 2 (1): sub1 called 2 times (total subscriber calls: 6)
END: sub1 called 2 times, all subscribers 6 times</pre>
<p>
  As expected there are six calls to subscribers, with each subscriber
  seeing two events. But there is an oddity in the order in which
  the subscribers see events.
</p>
<p>
  Not all subscribers receive the first event raised first,
  <code>sub2</code> receives event -1 before event 1: in
  reverse order. But <code>sub0</code> sees them in order.
  The only difference between the two subscribers is the
  order in which they were subscribed relative to
  <code>sub1</code>.
</p>
<p>
  Hence the comment above about a race-condition, and dependence
  on the implementation of <code>Subject&lt;T&gt;</code>. If a different
  container were used the order in which subscribers are called could be
  changed without any client code changing.
</p>
<p>
  Clearly the ordering between subscribers is subject to the scheduler
  in use, but a single subscriber seeing events in a different order
  certainly could be a problem. This is exacerbated by the dependence on
  when the subscription is performed. A concurrent system could have
  the relative order of subscription subject to external factors (e.g.
  how many cores, how slow an assembly is to load, &hellip;).
</p>

<h4>Next</h4>
<p>
  This post is now long enough, so my solution to this will wait for part 4.
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/02/04/observable-implementation-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable &quot;ObservableSource&quot; for the Reactive Extensions (part 2)</title>
		<link>http://blog.rjcox.co.uk/2010/01/24/observable-implementation-2/</link>
		<comments>http://blog.rjcox.co.uk/2010/01/24/observable-implementation-2/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 17:57:53 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=72</guid>
		<description><![CDATA[Introduction

  Continuing on from Observable1&#60;T&#62; implemented in 
  Part 1 with
  Observable2&#60;T&#62; here.


  The aim in this part is to allow re-entrant subscribe and unsubscribe operations to not fail.
  Using Observable1&#60;T&#62; a subscriber which tries to unsubscribe itself in its
  OnNext implementation will lead to an InvalidOperationException being
  [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>
  Continuing on from <code>Observable1&lt;T&gt;</code> implemented in 
  <a href="/2010/01/22/oberservable-implementation-1-2/">Part 1</a> with
  <code>Observable2&lt;T&gt;</code> here.
</p>
<p>
  The aim in this part is to allow re-entrant subscribe and unsubscribe operations to not fail.
  Using <code>Observable1&lt;T&gt;</code> a subscriber which tries to unsubscribe itself in its
  <code>OnNext</code> implementation will lead to an <code>InvalidOperationException</code> being
  thrown from <code>Observable1&lt;T&gt;.OnNext</code>. This is because <code>Subscribe</code> and
  <code>Unsubscribe</code> both modify the collection of subscribers in <code>Observable1&lt;T&gt;</code>
  and which <code>OnNext</code> is iterating over. The .NET Framework collections do not support this.
</p>

<h3>Supporting Re-entrant Operations</h3>
<p>
  To allow <code>Subscribe</code> and <code>Unsubscribe</code> to work is really very simple: just
  take a copy of the set of subscribers before iterating over it. Replacing the implementation of
  <code>Next</code> from <code>Observable1&lt;T&gt;</code>:
</p>
<pre>public void Next(T value) {
    foreach (var sub in subscribers.Values) {
        sub.OnNext(value);
    }
}</pre>
<p>
  with the following in <code>Observable2&lt;T&gt;</code> (full implementation is given
  <a href="#theCode">below</a>):
</p>
<pre>public void Next(T value) {
    var subs = subscribers.Values.ToArray();
    foreach (var sub in subs) {
        sub.OnNext(value);
    }
}</pre>
<p>
  And now code like the following doesn&rsquo;t fail:
</p>
<pre>bool hasUnsubscribed = false;
IDisposable unsub = null;
var sub = Observer.Create&lt;int&gt;(i =&gt; {
    Console.WriteLine("This is the subscriber, arg: {0}", i);
    if (unsub != null) {
        unsub.Dispose();
        unsub = null;
        hasUnsubscribed = true;
    }
});

var source = new Observable2&lt;int&gt;();
unsub = source.Subscribe(sub);
source.Next(1);
Assert.IsTrue(hasUnsubscribed);
Assert.IsNull(unsub);
</pre>
<p>
  <em>Note</em> this test code wouldn&rsquo;t pass with an arbitrary observable, where
  the requirement to allow asynchronous subscribe could lead to <code>unsub</code> not
  yet being set by the time the subscriber code is called (the null check will at least
  avoid the crash).
</p>
<p>
  While this seems an odd thing to do, consider a subscriber which just wants to react to
  one event (or the implementation of the RX operator <code>First</code>).
</p>

<h4>Progress Against the Overall Requirements</h4>
<p>See the <a href="/2010/01/10/iobservable-req/">full list of requirements</a>.</p>
<ul>
  <li><!--#1-->
    <p>
      #1: Manage subscribers: done. Can subscribe zero or more observers,
      and freely add or remove them.
    </p>
  </li>
  <li><!--#2-->
    <p>
      #2: OnNext, OnComplete and OnError: OnNext is done (will be called zero or more times).
      But neither completion or errors are supported, this also means that the source
      cannot indicate the end of events, every even sequence is currently infinite.
    </p>
  </li>
  <li><!--#3-->
    <p>
      #3 Exceptions from subscribers will fall back to the event producer: this will
      happen, but will also mean no other subscribers will see the event.
    </p>
    <p>
      Based on this
      <a href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/6bcf4737-721f-4f1a-96cc-a60f19b51610">forum
      thread</a>, about <code>Subject&lt;T&gt;</code>, the right
      approach here in Rx is not completely agreed.
    </p>
  </li>
  <li><!--#4-->
    <p>
      #4: Done: can freely add and remove subscribers.
    </p>
  </li>
  <li><!--#5-->
    <p>
      #5: Re-entrancy: this, part 2, makes a start. But a subscriber calling <code>Next</code>
      is likely to lead to some unexpected sequencing of calls.
    </p>
  </li>
</ul>

<a id='theCode'></a>
<h3>The <code>Observable2&lt;T&gt;</code> Implementation</h3>
<pre>using System;
using System.Collections.Generic;
using System.Linq;

public class Observable2&lt;T&gt; : IObservable&lt;T&gt; {
    private Dictionary&lt;int, IObserver&lt;T&gt;&gt; subscribers = new Dictionary&lt;int, IObserver&lt;T&gt;&gt;();
    private int nextSubscriber = 0;

    public IDisposable Subscribe(IObserver&lt;T&gt; observer) {
        subscribers.Add(nextSubscriber, observer);
        return new Observable1Disposer(this, nextSubscriber++);
    }

    private void Unsubscribe(int index) {
        subscribers.Remove(index);
    }

    public void Next(T value) {
        // To allow subscribers to unsubscribe while calling them, don't
        // directly iterate over the collection, but use a copy.
        var subs = subscribers.Values.ToArray();
        foreach (var sub in subs) {
            sub.OnNext(value);
        }
    }


    private class Observable1Disposer : IDisposable {
        private Observable2&lt;T&gt; target;
        private int index;
        internal Observable1Disposer(Observable2&lt;T&gt; target, int index) {
            this.target = target;
            this.index = index;
        }

        public void Dispose() {
            target.Unsubscribe(index);
        }
    }
}
</pre>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/01/24/observable-implementation-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Reusable &quot;ObservableSource&quot; for the Reactive Extensions (Part 1)</title>
		<link>http://blog.rjcox.co.uk/2010/01/22/observable-implementation-1/</link>
		<comments>http://blog.rjcox.co.uk/2010/01/22/observable-implementation-1/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 15:51:47 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=64</guid>
		<description><![CDATA[Introduction

  As seen in the requirements for an implementation
  of IObservable&#60;T&#62; there is a lot of ground to cover. So the idea is
  to start with a massively simplified subset of the requirements to better understand what
  is will take to implement the full requirements. In other words, a series of [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>
  As seen in the <a href="/2010/01/10/iobservable-req/">requirements for an implementation
  of <code>IObservable&lt;T&gt;</code></a> there is a lot of ground to cover. So the idea is
  to start with a massively simplified subset of the requirements to better understand what
  is will take to implement the full requirements. In other words, a series of partially
  functional prototypes.
</p>
<p>
  As a first step, just implement:
</p>
<ul>
  <li>Subscribe, and maintain a list of subscribed observers.</li>
  <li>
    A disposable helper type to act as a return from <code>Subscribe</code> to
    unsubscribe.
  </li>
  <li><code>Next</code> to call the <code>OnNext</code> of each subscriber</li>
</ul>
<p>
  This implementation does not:
</p>
<ul>
  <li>Handle concurrency.</li>
  <li>
    Support re-entrancy. Any call by a subscriber back into the Observable is, at best,
    going to fail.
  </li>
  <li>
    Make use of the rest of the <code>IObserver&lt;T&gt;</code> interface. No
    errors and no end to the events.
  </li>
  <li>
    Calling the subscribers asynchronously, in a synchronisation context of their (or the
    Reactive Framework's choice). (The 
    <code>System.Linq.Observable.ObserveOn&lt;T&gt;(IObservable&lt;T&gt; source,
    SynchronizationContext sync)</code> method of RX might be able to be used to
    work around this.)
  </li>
</ul>
<h3>Implementation</h3>
<pre class="code">using System;
using System.Collections.Generic;

public class Observable1&lt;T&gt; : IObservable&lt;T&gt; {
    private Dictionary&lt;int, IObserver&lt;T&gt;&gt; subscribers = new Dictionary&lt;int, IObserver&lt;T&gt;&gt;();
    private int nextSubscriber = 0;
    
    public IDisposable Subscribe(IObserver&lt;T&gt; observer) {
        subscribers.Add(nextSubscriber, observer);
        return new Observable1Disposer(this, nextSubscriber++);
    }

    private void Unsubscribe(int index) {
        subscribers.Remove(index);
    }

    public void Next(T value) {
        foreach (var sub in subscribers.Values) {
            sub.OnNext(value);
        }
    }


    private class Observable1Disposer : IDisposable {
        private Observable1&lt;T&gt; target;
        private int index;
        internal Observable1Disposer(Observable1&lt;T&gt; target, int index) {
            this.target = target;
            this.index = index;
        }

        public void Dispose() {
            target.Unsubscribe(index);
        }
    }
}</pre>

<h3>Testing</h3>
<p>
  Obviously I have some test code, but it all gets somewhat tedious very quickly as
  it covers all sorts of edge cases (e.g. check that subscribing and then unsubscribing
  before any events works&mdash;it does). So these are a couple of indicative samples.
</p>
<p>
  First what must be just about the simplest possible case, subscribe, one event and
  unsubscribe. Check that subscriber was called once:
</p>
<pre class="code">var calls = 0;
var sub = Observer.Create&lt;int&gt;(i =&gt; {
    Console.WriteLine("This is the subscriber, arg: {0}", i);
    ++calls;
});

var source = new Observable1&lt;int&gt;();
using (var disp = source.Subscribe(sub)) {
    source.Next(1);
}

if (calls != 1) {
    Console.WriteLine("Test FAILED");
}</pre>
<p>
  And then this to show that arbitrary interleaving of subscribe and unsubscribe operations
  will also work:
</p>
<pre class="code">var calls1 = 0;
var sub1 = Observer.Create&lt;int&gt;(i =&gt; {
    Console.WriteLine("This is subscriber #1, arg: {0}", i);
    ++calls1;
});
var calls2 = 0;
var sub2 = Observer.Create&lt;int&gt;(i =&gt; {
    Console.WriteLine("This is subscriber #2, arg: {0}", i);
    ++calls2;
});

var source = new Observable1&lt;int&gt;();
IDisposable disp1 = null, disp2 = null;
try {
    disp1 = source.Subscribe(sub1);
    disp2 = source.Subscribe(sub2);
    disp2.Dispose();
    source.Next(1); // sub1 gets this
    disp2 = source.Subscribe(sub2);
    source.Next(2); // sub1 and sub2 get this
    disp1.Dispose();
    source.Next(3); // sub2 gets this
    disp1 = source.Subscribe(sub1);
    source.Next(4); // Both get this
} finally {
    disp1.Dispose();
    disp2.Dispose();
}

if (calls1 != 3 || calls2 != 3) {
    Console.WriteLine("Test FAILED");
}</pre>
<p>
  In this second approach, I ended up adding the comments to the <code>Next()</code> calls to
  help me work out the counts. Then running and checking the console ensured all the events
  went to at least one subscriber. Clearly any real (production) code like this should be
  condemned with even the most limited of code reviews, but tests need to cover the bases.
</p>
<p>
  Both tests also show just how useful lambdas are when working with Rx, the ability to
  create test subscribers that are both inline with the test, and close over locals makes
  state handling much easier.
</p>

<h3>How this first <code>IObservable&lt;T&gt;</code> Is Inadequate</h3>
<p>
  Quick answer: in almost every way. Longer answer: while events are forwarded, and subscribers
  are managed the integrity of the system is only preserved by the subscribers playing by a very
  limited execution model. In particular no subscriber can unsubscribe in direct response to an
  event, because the iteration over the set of subscribers will fail if the <code>Subscribe</code>
  or <code>Unsubscribe</code> are called while in that iteration.
</p>

<h3>Next Steps</h3>
<p>
  Deal with the lack of re-entrancy, so a subscriber can be added or removed while events are being
  sent to the subscribers. Also use a test framework to make testing a little more integrated.
</p>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/01/22/observable-implementation-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Requirements for IObservable&lt;T&gt;</title>
		<link>http://blog.rjcox.co.uk/2010/01/10/iobservable-req/</link>
		<comments>http://blog.rjcox.co.uk/2010/01/10/iobservable-req/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 20:30:07 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[.NET Futures]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.rjcox.co.uk/?p=18</guid>
		<description><![CDATA[Introduction

  The recently released preview of the 
  Reactive Extensions (Rx) from Microsoft has had a lot of coverage from
  Channel 9.
  It includes support for compositional handling of observable event streams from:


  WinForms events,
  WPF events,
  the asynchronous pattern (BeginX and EndX method pairs), and
  an [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>
  The recently released preview of the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">
  Reactive Extensions (Rx)</a> from Microsoft has had a lot of coverage from
  <a href="http://channel9.msdn.com/tags/Rx/">Channel 9</a>.
  It includes support for compositional handling of observable event streams from:
</p>
<ul>
  <li>WinForms events,</li>
  <li>WPF events,</li>
  <li>the asynchronous pattern (<code>BeginX</code> and <code>EndX</code> method pairs), and</li>
  <li>an <code>IEnumerable&lt;T&gt;</code>.</li>
</ul>
<p>
  But it does not include anything reusable from which to build your own observable object. 
</p>
<p>
  This is unfortunate because it turns out creating an observable (a type implementing
  <code>IObservable&lt;T&gt;</code> is harder than it might be expected to be. It is certainly
  much more involved than implementing
  <code>IEnumerable&lt;T&gt;</code>/&#8203;<code>IEnumerator&lt;T&gt;</code>
  without using <code>yield</code> (as one needed to do to create a fully custom collection in .NET 1.0 and
  1.1).
</p>
<p>
  To start with one needs the requirements. There does not appear to be any explicit listing (yet), but
  from one source or another there is the information one needs. I've collected a few <a href="#sources">
  below</a>.
</p>

<h3>Requirements for an <code>IObservable&lt;T&gt;</code> Implementation</h3>
<p>
  In writing an implementation of IObservable&lt;T&gt; one should follow the documented semantics (the
  syntax is, of course, enforced by the compiler and runtime). And therefore be consistent
  with existing implementation, especially with the implementations contained within the Reactive Framework.
</p>
<p>
  The documentation for IObservable&lt;T&gt; is (currently, in preview release state) quite brief, but
  the sources listed below, and a little intuition can get a long way.
</p>
<ol>
  <li>
    <p>There will be zero or more subscribers.</p>
    <p>
      This does mean handling zero subscribers (all operations are no-ops) as well as handling many
      subscribers. This drives much of the implementation:
    </p>
    <ul>
      <li>Need a collection of subscribers.</li>
      <li>
        Need a mechanism for the object returned by the <code>Subscribe(<em>observer</em>)</code>
        to the subscriber to identify which subscriber is unsubscribing when
        <code>Dispose()</code> is called on that retuned object. This need to link back to a specific
        subscription means this disposable object cannot be trivial.
      </li>
      <li>
        Every event from the observable will require iterating through the list of subscribers. This
        needs to be both thread safe and re-entrant. In practice this means the observable needs to
        take a snapshot of the subscribers and iterate through that for each event (this makes use of
        the assumed asynchronous unsubscribe noted <a href="#asyncunsub">below</a>).
      </li>
    </ul>
  </li>
  <li>
    <p>
      A subscriber, which remains subscribed, will see zero or more calls to it's <code>OnNext</code>
      method maybe followed by <code>OnError</code> or <code>OnComplete</code>.
    </p>
    <p>In pseudo-regular-expression this could be: <code>OnNext*(OnError|OnComplete)?</code>.</p>
    <p>All the following patterns are acceptable</p>
    <ul>
      <li><em>nothing, no events at all</em>,</li>
      <li>OnNext one or more times (no OnComplete or OnError),</li>
      <li>Just OnComplete.</li>
    </ul>
  </li>
  <li>
    <p>
      Exceptions thrown by subscribers caused non-specified effects. It could do anything from nothing
      (i.e. observable absorbs them with a no-op <code>catch</code> block) to killing the whole
      process.
    </p>
    <p>
      This is more significant for subscribers: they should avoid throwing.
    </p>
  </li>
  <li>
    <p>
      Subscribers can be added or removed (via the <code>IDisposable</code> implementing object returned
      from the observable's <code>Subscribe</code> method).
    </p>
  </li>
  <li>
    <p>
      There is no restriction on the subscriber being notified, or any other piece of code, from calling
      into the observable. A subscriber (or other object called from the subscriber) or an entirely
      separate type on a different thread, can (directly or indirectly) call observable methods.
    </p>
    <p>
      For example it is quite acceptable for a subscriber to unsubscribe itself while handling a
      notification. For example:
    </p>
    <pre>
      var input = new[] { 1, 2, 3, 4, 5 };
      IDisposable d = null;
      var sub = Observer.Create<int>(x =&gt; {
          Console.WriteLine("Received {0}", x);
          d.Dispose();
      });
      d = input.Subscribe(sub);</pre>
    <p>
      In this code, one line is printed to the console.
    </p>
    <p>
      Strictly speaking the code above is incorrect. An observable could start sending events to the
      subscriber before <code>Subscribe</code> returns, thus <code>d</code> may not yet have a value
      when the <code>OnNext</code> is called. In this case that will lead to a
      <code>NullReferenceException</code>. This can be fixed by unsubscribing on the first
      event in which <code>d</code> has been set.
    </p>
  </li>
</ol>
<p>
  There are a couple of things the observable is <em>not</em> responsible for:
</p>
<ul>
  <li>
    <p>
      The observable does not need to ensure <code>Subscribe</code> returns <em>before</em>
      events are seen (as noted below the simple one-shot subscriber above).
    </p>
  </li>
  <li>
    <p>
      <a id='asyncunsub'></a>The observable does not need to complete an unsubscribe
      immediately. Rather the subscriber must handle receiving more events even after
      unsubscribing (this is true
      of .NET events as will always be an inherent race-condition when removing a listener).
    </p>
  </li>
</ul>

<a id='sources' ></a>
<h4>Sources of Requirements</h4>
<ol>
  <li>
    <p>
       <a href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/">"Reactive
       Extensions API in depth: Contract"</a> is directly from the team.
    </p>
    <p>It includes the following non-obvious points:</p>
    <ul>
      <li>
        <code>Subscribe(<em>subscriber</em>)</code> is asynchronous: the subscriber could start receiving
        events before the <code>IDisposable</code> with which to unsubscribe is returned.
      </li>
      <li>
        <code>Dispose()</code> of the object returned by <code>Subscribe(<em>subscriber</em>)</code>
        is also asynchronous: you may receive events from the observable after you have disposed
        the object.
      </li>
      <li>
        <code>IObservable&lt;T&gt;.Subscribe(<em>subscriber</em>)</code> must not throw. (I think this
        should be <em>should</em> not throw&mdash;after all out of memory and similar cannot be effectively
        be prevented in all cases.
      </li>
      <li>
        Exceptions from subscribers will not, in general, be caught (and fall through to the context
        of the observable).
      </li>
    </ul>
  </li>
  <li>
    <p>
      <a href="http://msdn.microsoft.com/library/dd990377(VS.100)"><code>IObservable&lt;T&gt;</code>
      documentation on MSDN</a>
    </p>
  </li>
  <li>
    <p>
      <a href="http://msdn.microsoft.com/library/dd783449(VS.100)"><code>IObserver&lt;T&gt;</code>
      documentation on MSDN</a>
    </p>
  </li>
  <li>
    <p>
      Blog posting <a href="http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!1767.entry">
      An RSS Dashboard in F#, part two (IObservables)</a> by Brian McNamara (2009-12-20).
    </p>
    <p>
      In F#, but the requirements for re-entrancy is clear.
    </p>
  </li>
  <li>
    <p>
      <a href="http://stackoverflow.com/questions/1768974/implementing-iobservablet-from-scratch">
      This question</a> on <a href="http://stackoverflow.com/">Stack Overflow</a> also has some
      useful information.
    </p>
  </li>
</ol>
<p>
  <strong>And next</strong>: on to an actual implementation.
</p>]]></content:encoded>
			<wfw:commentRss>http://blog.rjcox.co.uk/2010/01/10/iobservable-req/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

