Better PubSub example

This commit is contained in:
Vladimir Mihailenco 2018-07-24 14:50:16 +03:00
parent 480db94d33
commit 14aebdec92
1 changed files with 14 additions and 3 deletions

View File

@ -322,7 +322,6 @@ func ExampleClient_Watch() {
func ExamplePubSub() {
pubsub := client.Subscribe("mychannel1")
defer pubsub.Close()
// Wait for confirmation that subscription is created before publishing anything.
_, err := pubsub.Receive()
@ -339,8 +338,20 @@ func ExamplePubSub() {
panic(err)
}
msg := <-ch
fmt.Println(msg.Channel, msg.Payload)
time.AfterFunc(time.Second, func() {
// When pubsub is closed channel is closed too.
_ = pubsub.Close()
})
// Consume messages.
for {
msg, ok := <-ch
if !ok {
break
}
fmt.Println(msg.Channel, msg.Payload)
}
// Output: mychannel1 hello
}