opts.go 1.53 KB
Newer Older
Łukasz Magiera's avatar
Łukasz Magiera committed
1 2
package event

Łukasz Magiera's avatar
Łukasz Magiera committed
3 4 5 6 7
import (
	"errors"
	"reflect"
)

Raúl Kripalani's avatar
Raúl Kripalani committed
8 9 10 11
type SubscriptionOpt = func(interface{}) error

type EmitterOpt = func(interface{}) error

Łukasz Magiera's avatar
Łukasz Magiera committed
12
type subSettings struct {
Łukasz Magiera's avatar
Łukasz Magiera committed
13 14
	forcedType reflect.Type
}
Raúl Kripalani's avatar
Raúl Kripalani committed
15

Łukasz Magiera's avatar
Łukasz Magiera committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// 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)))
// [...]
Raúl Kripalani's avatar
Raúl Kripalani committed
32
func ForceSubType(evtType interface{}) SubscriptionOpt {
Raúl Kripalani's avatar
Raúl Kripalani committed
33 34
	return func(settings interface{}) error {
		s := settings.(*subSettings)
Łukasz Magiera's avatar
Łukasz Magiera committed
35 36 37 38 39 40 41 42
		typ := reflect.TypeOf(evtType)
		if typ.Kind() != reflect.Ptr {
			return errors.New("ForceSubType called with non-pointer type")
		}
		s.forcedType = typ
		return nil
	}
}
43

Łukasz Magiera's avatar
Łukasz Magiera committed
44
type emitterSettings struct {
Łukasz Magiera's avatar
Łukasz Magiera committed
45 46
	makeStateful bool
}
47

Łukasz Magiera's avatar
Łukasz Magiera committed
48 49 50 51 52 53 54
// 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
Łukasz Magiera's avatar
Łukasz Magiera committed
55 56 57
func Stateful(s interface{}) error {
	s.(*emitterSettings).makeStateful = true
	return nil
Łukasz Magiera's avatar
Łukasz Magiera committed
58
}