title: Mutable State and the Observer Pattern
body: <p>I'm currently redeveloping an application in F# and, while the experience has been excellent, I find myself a little bewildered when it comes to controlling mutability.</p>
  
  <p>Previously, the document model used by my C# program was highly mutable and implemented ObservableCollections and INotifyPropertyChanged that shared state between views wouldn't bug out. Clearly, this isn't an ideal, especially if I want a fully immutable approach to my designs.</p>
  
  <p>With that in mind I created a non-observable, immutable, document model for my underlying application kernel but, because I want a UI subscriber to see changes I immediately found myself implementing event-driven patterns:</p>
  
  <pre><code>// Raw data.
  type KernelData = { DocumentContent : List&lt;string&gt; }
  
  // Commands that act on the data.
  type KernelCommands = { AddString : string -&gt; () }
  
  // A command implementation. Performs a state change, echos the new state through the event.
  let addStringCommand (kernelState : KernelData) (kernelChanged : Event&lt;KernelData&gt;) (newString : string) =
      kernelState with { DocumentContent=oldList |&gt; List.add newString }
      |&gt; kernelChanged.Trigger
  
  // Time to wire this up.
  do
      // Create some starting state.
      let kernelData = { DocumentContent=List.Empty }
  
      // Create a shared event that commands may use to inform observers (UI).
      let kernelChangedEvent = new Event&lt;KernelData&gt;()
  
      // Create the command, it uses the event to inform observers.
      let kernelCommands = { AddString=addString kernelData kernelChangedEvent }
  
      // Create a UI element that uses the commands to initialize data transformations. UI elements subscribed to the data use the event to listen.
      let myUI = new UiObject(kernelData, kernelChangedEvent.Publish, kernelCommands)
      myUI.Show()
  </code></pre>
  
  <p>So this has been my solution to passing new state to the relevant listeners. However, what would be more ideal is a "box" I can "hook" into with transform functions. When the box mutates, functions are called to deal with the new state and produce corresponding changed state in a UI component. </p>
  
  <pre><code>do
      // Lambda called whenever the box changes.
      idealBox &gt;&gt;= (fun newModel -&gt; new UIComponent(newModel))
  </code></pre>
  
  <p>So I guess I'm asking if there is an observable pattern for dealing with these situations. Mutable state is normally handled using monads but I've only seen examples which involve performing the operation (e.g. piping console IO monads, loading files, etc.) and not actually dealing with persistently mutating state.</p>