opts.go 1.51 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"
)

Łukasz Magiera's avatar
Łukasz Magiera committed
8
type subSettings struct {
Łukasz Magiera's avatar
Łukasz Magiera committed
9 10
	forcedType reflect.Type
}
Raúl Kripalani's avatar
Raúl Kripalani committed
11 12

type SubOption func(interface{}) error
Łukasz Magiera's avatar
Łukasz Magiera committed
13

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

Łukasz Magiera's avatar
Łukasz Magiera committed
42
type emitterSettings struct {
Łukasz Magiera's avatar
Łukasz Magiera committed
43 44
	makeStateful bool
}
Raúl Kripalani's avatar
Raúl Kripalani committed
45
type EmitterOption func(interface{}) error
46

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