func pubsub()

in get-started-with-redis/pubsub.go [124:164]


func pubsub(client *redis.Client) (err error) {
	ctx := context.Background()

	// Step 1: subscribe each team
	teams := getTeams(client)
	for i := 0; i < 3; i++ {
		err = teams[i].subscribe()
		if err != nil {
			return fmt.Errorf("subscribing failed: %w", err)
		}
	}

	// Step 2: publish challenges
	// Read the challenges from the sorted set "challenges" and publish them
	for i := int64(0); i < 5; i++ {
		challenge := client.ZRange(ctx, "challenges", i, i).Val()[0]
		err = publish(client, challenge)
		if err != nil {
			return fmt.Errorf("cannot publish challenge %s: %w", challenge, err)
		}
	}
	// Close the channel after one second, to terminate the receive loops.
	time.AfterFunc(time.Second, func() {
		teams[0].channel.Close()
		fmt.Println(`PubSub channel "challenges" closed`)
	})

	// Step 3: receive published messages
	rch := make(chan Res)
	for i := 0; i < 3; i++ {
		go teams[i].receive(ctx, rch)
	}
	for msg := range rch {
		if msg.err != nil {
			return fmt.Errorf("cannot receive challenge: %w", msg.err)
		}
		fmt.Println(msg.result)
	}

	return nil
}