forked from libp2p/go-libp2p-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscription.go
52 lines (44 loc) · 1.15 KB
/
subscription.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package pubsub
import (
"context"
"sync"
ss "github.com/pancsta/go-libp2p-pubsub/states/pubsub"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
)
// Subscription handles the details of a particular Topic subscription.
// There may be many subscriptions for a given Topic.
type Subscription struct {
topic string
ch chan *Message
psMach *am.Machine
ctx context.Context
err error
once sync.Once
//mach *am.Machine
}
// Topic returns the topic string associated with the Subscription
func (sub *Subscription) Topic() string {
return sub.topic
}
// Next returns the next message in our subscription
func (sub *Subscription) Next(ctx context.Context) (*Message, error) {
select {
case msg, ok := <-sub.ch:
if !ok {
return msg, sub.err
}
return msg, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Cancel closes the subscription. If this is the last active subscription then pubsub will send an unsubscribe
// announcement to the network.
func (sub *Subscription) Cancel() {
sub.psMach.Add1(ss.RemoveSubscription, am.A{"Subscription": sub})
}
func (sub *Subscription) close() {
sub.once.Do(func() {
close(sub.ch)
})
}