Observable Package
pocket/pkg/observable Package
pocket/pkg/observable PackageThe pocket/pkg/observable package provides a lightweight and straightforward mechanism to handle asynchronous notifications using the Observer pattern. This is achieved through two primary interfaces: Observable and Observer.
Overview
The Observable interface is responsible for notifying multiple subscribers about new values asynchronously, while the Observer interface allows access to the notified channel and facilitates unsubscribing from an Observable.
Interfaces and Structures
Observable Interface
Observable InterfaceRepresents a publisher in a "Fan-Out" system design, allowing multiple subscribers to be notified of new values asynchronously.
Methods:
Subscribe: Used to subscribe an observer to the observable. Returns an instance of the
Observerinterface.{% code title="Subscribe signature" %}
func (o *MyObservableType) Subscribe(ctx context.Context) Observer[MyValueType]{% endcode %}
UnsubscribeAll: Unsubscribes all observers from the observable.
{% code title="UnsubscribeAll signature" %}
func (o *MyObservableType) UnsubscribeAll(){% endcode %}
Observer Interface
Observer InterfaceRepresents a subscriber in a "Fan-Out" system design, providing access to the notified channel and capabilities to unsubscribe.
Methods:
Unsubscribe: Used to unsubscribe the observer from its associated observable.
{% code title="Unsubscribe signature" %}
{% endcode %}
Ch: Returns the channel through which the observer receives notifications.
{% code title="Ch signature" %}
{% endcode %}
Architecture Diagrams
Visual representations to explain high-level structure and interactions.
Observable Synchronization
Figure 1: This diagram depicts the synchronization mechanisms between the observable and its observers. It specifically showcases the use of read and write locks for different operations in both observable and observer contexts.
Observable Buffering
Figure 2: The diagram illustrates the buffering mechanisms within the observable and its observers. It highlights how published messages are buffered and how they propagate to the individual observers' buffers.
Usage
Basic Example
Considerations
Conclusion
The pkg/observable package is an intuitive solution for handling asynchronous notifications in Go projects, ensuring efficient communication between observables and observers.
Was this helpful?
