Grodriguez
Grodriguez

Reputation: 21995

Publishing initial state in Observer pattern

Is there a preferred idiom for publishing the "initial state" to new observers in the Observer pattern?

Most of the available material and examples describing the Observer pattern assume that observers are interested in being notified of changes, but don't care about the "initial state" (the current state at the time observers subscribe to changes).

One possibility would be to push the "initial" (current) state to new observers when they subscribe, e.g.:

public class MyObservable extends java.util.Observable
{
    public synchronized void addObserver(Observer observer)
    {
        super.addObserver(observer);

        // Push current state to this observer
        observer.update(this, currentState);
    }
}

Is there a better / preferred approach?

Upvotes: 5

Views: 664

Answers (2)

jan
jan

Reputation: 1601

I don't know if it can be considered preferred,
but in the context of Reactive Extensions' "hot observables", the idiom "Replay" is used:

Short demo (C#):

using System;
using System.Reactive.Linq;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var observable = Observable.Interval(TimeSpan.FromSeconds(1))
        .Do(l => Console.WriteLine("Publishing {0}", l))  //side effect to show it is running
        .Replay(1);                                       // buffer the last entry

      Console.ReadKey();

      using (observable.Connect())                        // turn it "hot"
      {
        Console.ReadKey();

        observable.Subscribe(i => Console.WriteLine("OnNext #1: {0}", i));

        Console.ReadKey();

        using (observable.Subscribe(i => Console.WriteLine("OnNext #2: {0}", i)))
        {
          Console.ReadKey();
        }                                                 // unsubscribes #2 again

        Console.ReadKey();
      }                                                   // turn it "cold"

      Console.ReadKey();
    }
  }
}

Output:

     Publishing 0
    Publishing 1
    Publishing 2
     OnNext #1: 2
    Publishing 3
    OnNext #1: 3
    Publishing 4
    OnNext #1: 4
    Publishing 5
    OnNext #1: 5
     OnNext #2: 5
    Publishing 6
    OnNext #1: 6
    OnNext #2: 6
    Publishing 7
    OnNext #1: 7
    OnNext #2: 7
    Publishing 8
    OnNext #1: 8
    OnNext #2: 8
     Publishing 9
    OnNext #1: 9
    Publishing 10
    OnNext #1: 10

Upvotes: 1

Anders Johansen
Anders Johansen

Reputation: 10455

Not really. But usually there's some configuration file or default settings at the root of your observer hierarchy, and so the initial cascade of events will be set off when those are read/set.

The tricky bit is to make sure that all settings are grouped so that the observable entities are set in an order that is "legal", or at least works the way you expect.

Upvotes: 1

Related Questions