Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 859
Grodriguez Avatar asked Nov 03 '22 15:11

Grodriguez


1 Answers

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
like image 92
jan Avatar answered Nov 18 '22 00:11

jan