tags:

views:

170

answers:

1

This problem is pretty common: an object should notify all its subscribers when some event occurs. In C++ we may use boost::signals or something else. But how to do this in Go language? It would be nice to see some working code example where a couple of objects are subscribed to a publisher and process notifications.

Thanks

+2  A: 

This is actually pretty simple in Go. Use channels. This is the kind of thing they're made for.

type Publish struct {
    listeners []chan *Msg
}

type Subscriber struct {
    Channel chan *Msg
}

func (p *Publisher) Sub(c chan *Msg) {
    p.appendListener(c)
}

func (p *Publisher) Pub(m *Msg) {
    for _, c := range p.listeners {
        c <- Msg
    }
}

func (s *Subscriber) ListenOnChannel() {
    for {
        data := <-s.Channel
        //Process data
    }
}

func main() {
    for _, v := range subscribers {
        p.Sub(v.Channel)
        go v.ListenOnChannel()
    }
    //Some kind of wait here
}

Obviously this isn't exactly a working code sample. But it's close.

cthom06
Be careful with blocking channel operations.
MizardX
@MizardX of course, normally I'd have control chan's as well, like chan bool and use select {}, and quit on a recv from the control channel. But that's all fairly trivial and a bit excessive for a basic example.
cthom06
@MizardX: isn't that a bit like saying "be careful with pointer arithmetic" in C? Being careful with channels is 90% of Go programming ;-)
Steve Jessop