F7: Observer pattern + Events Flashcards
What are the key points of observer patterns?
- Observer patterns allows objects, termed ‘observers’, to listen for and be notified of changes in another object known as the ‘observable’ or the ‘subject’.
- It lays the groundwork for many advanced programming concepts such as events and real-world applications.
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
- Vad kallas IObservable< T > och IObserver< T > i följande kod:
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:
- A data source (the “observable”) produces data over time.
- One or more listeners (the “observers”) are interested in that data.
- When the observable has a new piece of data, it pushes that data to its observers using the OnNext method. If there’s an error during the production of data, the observable can notify the observers about it using the OnError method.
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.