diff --git a/README.md b/README.md index cc4d03a..be6fdf5 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ go get -u gitlab.com/naterciom/gubgub ## Example +Ignoring errors for code brevity! + ```Go package main @@ -31,20 +33,16 @@ func consumer(msg MyMessage) { } func main() { - ctx, cancel := context.WithTimeout(context.TODO(), time.Second) - defer cancel() + topic := gubgub.NewAsyncTopic[MyMessage]() + defer topic.Close() // Returns after all messages are delivered - topic := gubgub.NewAsyncTopic[MyMessage](ctx) - - topic.Subscribe(gubgub.Forever(consumer)) + _ := topic.Subscribe(gubgub.Forever(consumer)) // The AsyncTopic doesn't wait for the subscriber to be registered so, for the purposes of this // example, we sleep on it. time.Sleep(time.Millisecond) - topic.Publish(MyMessage{Name: "John Smith"}) - - <-ctx.Done() + _ := topic.Publish(MyMessage{Name: "John Smith"}) // Returns immediately } ``` ## Topics diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..6ad531c --- /dev/null +++ b/example/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "bufio" + "fmt" + "log" + "os" + "strings" + "time" + + "gitlab.com/naterciom/gubgub" +) + +func main() { + topic := gubgub.NewAsyncTopic[string]() + defer topic.Close() + + topic.Subscribe(gubgub.Forever(UpperCaser)) + + topic.Subscribe(Countdown(3)) + + topic.Subscribe(gubgub.Buffered(gubgub.Forever(Slow))) + + fmt.Printf("Use 'Ctrl+C' to exit! Type messages followed by 'Enter' to publish them:\n") + scanner := bufio.NewScanner(os.Stdin) + for { + scanner.Scan() + err := scanner.Err() + if err != nil { + log.Fatal(err) + } + topic.Publish(scanner.Text()) + } +} + +func UpperCaser(input string) { + log.Printf("UpperCaser: %s", strings.ToUpper(input)) +} + +func Countdown(count int) gubgub.Subscriber[string] { + return func(_ string) bool { + count-- + if count > 0 { + log.Printf("Countdown: %d...", count) + return true + } else { + log.Print("Countdown: I'm out!") + return false + } + } +} + +func Slow(input string) { + time.Sleep(time.Second * 3) + log.Printf("Slow: %s", input) +}