Skip to content

Commit

Permalink
issue-32: Add an example of using a bell with context
Browse files Browse the repository at this point in the history
  • Loading branch information
lowitea committed Apr 29, 2022
1 parent 571bef0 commit b9a5586
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package bell_test

import (
"context"
"fmt"
"github.com/nuttech/bell/v2"
"sort"
"time"
)

type CustomStruct struct {
Expand All @@ -12,7 +14,7 @@ type CustomStruct struct {
}

func Example() {
// Example of use via global state
// Use via global state

event := "event_name"
event2 := "event_name_2"
Expand Down Expand Up @@ -56,7 +58,7 @@ func Example() {
}

func ExampleEvents() {
// Example of use struct (without global state)
// Use events object (without global state)

eventName := "event_name"

Expand All @@ -75,3 +77,44 @@ func ExampleEvents() {
// Output:
// Hello bell!
}

func Example_usingContext() {
// Use bell with context

// create a custom struct for pass a context
type Custom struct {
ctx context.Context
value interface{}
}

// add listener
bell.Listen("event", func(message bell.Message) {
for iterationsCount := 1; true; iterationsCount++ {
select {
case <-message.(*Custom).ctx.Done():
return
default:
fmt.Printf("Iteration #%d\n", iterationsCount)
time.Sleep(10 * time.Second)
}
}
})

// create a global context for all calls
globalCtx, cancelGlobalCtx := context.WithCancel(context.Background())

// create a children context for a call with timeout
ringCtx, ringCancel := context.WithTimeout(globalCtx, time.Minute)
defer ringCancel()

_ = bell.Ring("event", &Custom{ringCtx, "value"})

// wait a second for the handler to perform one iteration
time.Sleep(time.Second)

// interrupt all handlers
cancelGlobalCtx()

// Output:
// Iteration #1
}

0 comments on commit b9a5586

Please sign in to comment.