From 14aebdec9279027d2d629d5a293a0e73449b999e Mon Sep 17 00:00:00 2001 From: Vladimir Mihailenco Date: Tue, 24 Jul 2018 14:50:16 +0300 Subject: [PATCH] Better PubSub example --- example_test.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/example_test.go b/example_test.go index c3ac33f..b92c603 100644 --- a/example_test.go +++ b/example_test.go @@ -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 }