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

Łukasz Magiera's avatar
Łukasz Magiera committed
3 4 5
import (
	"errors"
	"reflect"
Raúl Kripalani's avatar
Raúl Kripalani committed
6

Raúl Kripalani's avatar
Raúl Kripalani committed
7 8
	"github.com/libp2p/go-libp2p-core/event"
)
Raúl Kripalani's avatar
Raúl Kripalani committed
9

Łukasz Magiera's avatar
Łukasz Magiera committed
10
type subSettings struct {
Łukasz Magiera's avatar
Łukasz Magiera committed
11 12
	forcedType reflect.Type
}
Raúl Kripalani's avatar
Raúl Kripalani 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)))
// [...]
Raúl Kripalani's avatar
Raúl Kripalani committed
30
func ForceSubType(evtType interface{}) event.SubscriptionOpt {
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
}
45

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