An open API service indexing awesome lists of open source software.

https://github.com/lestrrat-go/pubsub

Simple broadcast pattern
https://github.com/lestrrat-go/pubsub

Last synced: 4 months ago
JSON representation

Simple broadcast pattern

Awesome Lists containing this project

README

        

pubsub
=========

Simple pubsub framework for Go.

This is (should be, fingers crossed) safe to be used from multiple goroutines. Designed such that only one goroutine makes changes to the object structure

```go
var svc pubsub.Service

// Create a Loopback object for in-memory broadcasting.
// You can create similar publishing mechanism for gRPC, or whatever.
l := pubsub.NewLoopback(&svc)

var msgs []interface{}
// You can create your own subscriber, of course, but this
// is the built-in hack to allow closures (eek)
sub := pubsub.SubscribeFunc(func(v interface{}) {
msgs = append(msgs, v)
})

// Subscribing before starting the main loop is safe
svc.Subscribe(sub)

// Sending before starting the main loop is safe
l.Send(`Hello`)

ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()

// Start the main loop
go svc.Run(ctx)

// Sending after starting the main loop.. is obviously safe.
l.Send(`World!`)

// If you have another subscriber, you can add it here.
// It will only receive subsequent pubsub requests
// svc.Subscribe(sub2)
```