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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With