What are the key points of observer patterns?
What is the “definition” of observer patterns?
To define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Dvs. One to Many
Why does observer patterns promote loose coupling between objects?
It promotes loose coupling because the observable doesn’t need to know anything specific about its observers, and observers can be added or removed at run-time without affecting the observable’s core functionality.
Vad innebär loose coupling?
ex.
* Observable behöver bara känna till observers interface
* Observer behöver inte känna till observable, dvs. den som skickar meddelandet
* Observers kan läggas till och tas bort under körning
(Tänk +unregisterObserver och +registerObserver)
Vad används observer patterns/events vanligtvis till?
De används för att strukturera flödet långt “ute” i apploikationen
Interface IObservable< T >
{
IDisposable Subscribe (IObserver< T >);
}
IObservable< T > = typ-parameter
IObserver< T > = typ-argument
Vad är poängen med raden:
void onError (Exception error) ;
i följande kod:
interface IObserver<T>
{
void OnCompleted ();
void OnError (Exception error);
void OnNext (T value);
}
OnError (Exception Error) har meningen med att kommunicera med subscribers att det har skett ett error, dvs. Utan OnError hade endast “observable”(ex. podcasten) fått errormeddelandet.
Exempel:
Why is OnError so important?
The OnError method is essential for robust applications because it provides a mechanism to handle or respond to errors that occur during the data production process.
Instead of crashing or ignoring the error, the observable communicates the error to its subscribers, allowing them to take appropriate actions, whether it’s logging, retrying, or alerting the user.