go-libp2p-pubsub/subscription.go

48 lines
1006 B
Go
Raw Normal View History

package pubsub
2016-10-19 23:01:06 +00:00
2016-11-17 10:27:57 +00:00
import (
"context"
)
// Subscription handles the details of a particular Topic subscription.
// There may be many subscriptions for a given Topic.
2016-10-19 23:01:06 +00:00
type Subscription struct {
topic string
ch chan *Message
cancelCh chan<- *Subscription
2019-09-30 09:55:37 +00:00
ctx context.Context
err error
2016-10-19 23:01:06 +00:00
}
// Topic returns the topic string associated with the Subscription
2016-10-19 23:01:06 +00:00
func (sub *Subscription) Topic() string {
return sub.topic
}
// Next returns the next message in our subscription
2016-11-17 10:27:57 +00:00
func (sub *Subscription) Next(ctx context.Context) (*Message, error) {
select {
case msg, ok := <-sub.ch:
if !ok {
return msg, sub.err
}
2016-10-19 23:01:06 +00:00
2016-11-17 10:27:57 +00:00
return msg, nil
case <-ctx.Done():
return nil, ctx.Err()
2016-10-19 23:01:06 +00:00
}
}
// Cancel closes the subscription. If this is the last active subscription then pubsub will send an unsubscribe
// announcement to the network.
2016-10-19 23:01:06 +00:00
func (sub *Subscription) Cancel() {
2019-09-30 09:55:37 +00:00
select {
case sub.cancelCh <- sub:
case <-sub.ctx.Done():
}
2016-10-19 23:01:06 +00:00
}
2019-07-01 15:43:49 +00:00
func (sub *Subscription) close() {
2019-06-21 06:46:41 +00:00
close(sub.ch)
}