Fixed example and added an example program

This commit is contained in:
2024-09-09 12:11:47 +01:00
parent 12024e3156
commit 087bf1952d
2 changed files with 62 additions and 8 deletions

View File

@@ -11,6 +11,8 @@ go get -u gitlab.com/naterciom/gubgub
## Example ## Example
Ignoring errors for code brevity!
```Go ```Go
package main package main
@@ -31,20 +33,16 @@ func consumer(msg MyMessage) {
} }
func main() { func main() {
ctx, cancel := context.WithTimeout(context.TODO(), time.Second) topic := gubgub.NewAsyncTopic[MyMessage]()
defer cancel() 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 // The AsyncTopic doesn't wait for the subscriber to be registered so, for the purposes of this
// example, we sleep on it. // example, we sleep on it.
time.Sleep(time.Millisecond) time.Sleep(time.Millisecond)
topic.Publish(MyMessage{Name: "John Smith"}) _ := topic.Publish(MyMessage{Name: "John Smith"}) // Returns immediately
<-ctx.Done()
} }
``` ```
## Topics ## Topics

56
example/main.go Normal file
View File

@@ -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)
}