Publish an initial state in an Observer template

Is there a preferred idiom for posting an “initial state” for new observers in the Observer pattern?

Most of the available materials and examples describing the Observer pattern suggest that observers are interested in notifying about changes, but do not care about the “initial state” (the current state when observers subscribe to changes).

One possibility would be to click on the “initial” (current) state on new observers when signing them, for example:

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?

+4
source share
2 answers

Not really. But usually in the root of your observer hierarchy there is some configuration file or default settings, so the initial cascade of events will be disabled when they are read / installed.

The tricky bit is to make sure that all parameters are grouped so that the monitored objects are set in a manner that is “legal” or at least works as you expect.

+1
source

I don’t know if it can be considered preferable,
but in the context of Reactive Extensions "hot observables", the idiom " Replay ":

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 
0
source

Source: https://habr.com/ru/post/1436095/


All Articles