go-libp2p-pubsub/subscription.go

48 lines
1006 B
Go
Raw Normal View History

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