Documentation ¶
Overview ¶
Package events provides a simple and effective implementation of event system.
Event is a battle proven way to decoupling services. Package event calls event listeners in a synchronous, sequential execution. The synchronous listener is only a "go" away from an asynchronous handler, but asynchronous listener can not be easily made synchronous.
The event listeners can also be used as hooks. If the event data is a pointer type, listeners may alter the data. This enables plugin/addon style decoupling.
Note: Package event focus on events within the system, not events outsource to eternal system. For that, use a message queue like kafka.
Example ¶
package main import ( "context" "fmt" "github.com/DoNewsCode/core/contract" "github.com/DoNewsCode/core/events" ) func main() { dispatcher := &events.SyncDispatcher{} // Subscribe to int event. dispatcher.Subscribe(events.Listen(events.From(0), func(ctx context.Context, event contract.Event) error { fmt.Println(event.Data()) return nil })) // Subscribe to string event. dispatcher.Subscribe(events.Listen(events.From(""), func(ctx context.Context, event contract.Event) error { fmt.Println(event.Data()) return nil })) dispatcher.Dispatch(context.Background(), events.Of(100)) dispatcher.Dispatch(context.Background(), events.Of("event")) }
Output: 100 event
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Event ¶
type Event struct {
// contains filtered or unexported fields
}
Event is a thin wrapper for events. It implements contract.Event for any interface.
type SyncDispatcher ¶
type SyncDispatcher struct {
// contains filtered or unexported fields
}
SyncDispatcher is a contract.Dispatcher implementation that dispatches events synchronously. SyncDispatcher is safe for concurrent use.
func (*SyncDispatcher) Dispatch ¶
Dispatch dispatches events synchronously. If any listener returns an error, abort the process immediately and return that error to caller.
func (*SyncDispatcher) Subscribe ¶
func (d *SyncDispatcher) Subscribe(listener contract.Listener)
Subscribe subscribes the listener to the dispatcher.