2019-06-13 10:23:03 +08:00
|
|
|
package event
|
|
|
|
|
2019-06-17 00:15:35 +08:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
2019-06-19 20:22:10 +08:00
|
|
|
type subSettings struct {
|
2019-06-17 00:15:35 +08:00
|
|
|
forcedType reflect.Type
|
|
|
|
}
|
2019-06-19 21:08:16 +08:00
|
|
|
|
|
|
|
type SubOption func(interface{}) error
|
2019-06-17 00:15:35 +08:00
|
|
|
|
2019-06-19 20:13:48 +08:00
|
|
|
// ForceSubType is a Subscribe option which overrides the type to which
|
|
|
|
// the subscription will be done. Note that the evtType must be assignable
|
|
|
|
// to channel type.
|
|
|
|
//
|
|
|
|
// This also allows for subscribing to multiple eventbus channels with one
|
|
|
|
// Go channel to get better ordering guarantees.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
// type Event struct{}
|
|
|
|
// func (Event) String() string {
|
|
|
|
// return "event"
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// eventCh := make(chan fmt.Stringer) // interface { String() string }
|
|
|
|
// cancel, err := eventbus.Subscribe(eventCh, event.ForceSubType(new(Event)))
|
|
|
|
// [...]
|
2019-06-17 00:15:35 +08:00
|
|
|
func ForceSubType(evtType interface{}) SubOption {
|
2019-06-19 21:08:16 +08:00
|
|
|
return func(settings interface{}) error {
|
|
|
|
s := settings.(*subSettings)
|
2019-06-17 00:15:35 +08:00
|
|
|
typ := reflect.TypeOf(evtType)
|
|
|
|
if typ.Kind() != reflect.Ptr {
|
|
|
|
return errors.New("ForceSubType called with non-pointer type")
|
|
|
|
}
|
|
|
|
s.forcedType = typ
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2019-06-13 16:04:12 +08:00
|
|
|
|
2019-06-19 20:22:10 +08:00
|
|
|
type emitterSettings struct {
|
2019-06-17 03:42:47 +08:00
|
|
|
makeStateful bool
|
|
|
|
}
|
2019-06-19 21:08:16 +08:00
|
|
|
type EmitterOption func(interface{}) error
|
2019-06-13 16:04:12 +08:00
|
|
|
|
2019-06-19 20:13:48 +08:00
|
|
|
// Stateful is an Emitter option which makes makes the eventbus channel
|
|
|
|
// 'remember' last event sent, and when a new subscriber joins the
|
|
|
|
// bus, the remembered event is immediately sent to the subscription
|
|
|
|
// channel.
|
|
|
|
//
|
|
|
|
// This allows to provide state tracking for dynamic systems, and/or
|
|
|
|
// allows new subscribers to verify that there are Emitters on the channel
|
2019-06-19 21:36:31 +08:00
|
|
|
func Stateful(s interface{}) error {
|
|
|
|
s.(*emitterSettings).makeStateful = true
|
|
|
|
return nil
|
2019-06-17 03:42:47 +08:00
|
|
|
}
|