Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update topics example to illustrate how to wait for subscription close #511

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions examples/topic-example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package main

import (
"context"
"errors"
"fmt"
"sync"
"time"

"github.com/momentohq/client-sdk-go/auth"
Expand Down Expand Up @@ -33,24 +35,42 @@ func main() {
panic(err)
}

// Receive and print messages in a goroutine
go func() { pollForMessages(ctx, sub) }()
var pollForMessagesWg sync.WaitGroup
pollForMessagesWg.Add(1)

// Receive and print all events in a goroutine
// go func() { pollForEvents(ctx, sub) }()
// Receive and print messages in a goroutine
go func() {
defer pollForMessagesWg.Done()
pollForMessages(ctx, sub)
}()

// Alternately, receive and print all events in a goroutine. Events include Items as well as other message types
// such as heartbeats and discontinuities.
//go func() {
// defer pollForMessagesWg.Done()
// pollForEvents(ctx, sub)
//}()

time.Sleep(time.Second)

// Publish messages for the subscriber
publishMessages(topicClient, ctx)

sub.Close()

fmt.Printf("closed subscription, waiting for pollForMessages wg\n")
pollForMessagesWg.Wait()
fmt.Printf("pollForMessages wg done\n")
}

func pollForMessages(ctx context.Context, sub momento.TopicSubscription) {
for {
item, err := sub.Item(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
fmt.Printf("pollForMessages context canceled\n")
break
}
panic(err)
}
switch msg := item.(type) {
Expand All @@ -66,6 +86,10 @@ func pollForEvents(ctx context.Context, sub momento.TopicSubscription) {
for {
event, err := sub.Event(ctx)
if err != nil {
if errors.Is(err, context.Canceled) {
fmt.Printf("pollForEvents context canceled\n")
break
}
panic(err)
}
switch e := event.(type) {
Expand Down
Loading