Subscribe to a query

The generated SDK has a SubscribeTo method for each exported query. The first result that a subscription delivers is the current result. After each commit that changes a field that the query reads, the subscription delivers the new complete result.

Create subscribe/main.go with this program. It subscribes to houses. A goroutine prints the number of houses in each result. It stops when a result includes House Harkonnen. The main program founds House Harkonnen and waits for the goroutine to stop.

go912 B
package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"example.com/quickstart/sdk"
)

func main() {
	db, err := sdk.Open(sdk.Config{Plugins: &sdk.Plugins{
		Stdlib:   true,
		Database: &sdk.DatabaseSettings{Path: "dune.db"},
	}})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	sub, err := db.DuneHouses.SubscribeToHouses()
	if err != nil {
		log.Fatal(err)
	}
	defer sub.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for event, err := range sub.Events(ctx) {
			if err != nil {
				log.Print(err)
				return
			}
			fmt.Printf("houses: %d\n", len(event.Result))
			for _, house := range event.Result {
				if house.Name == "Harkonnen" {
					return
				}
			}
		}
	}()

	_, err = db.DuneHouses.AtomicsFound("Harkonnen")
	if err != nil {
		log.Fatal(err)
	}
	wg.Wait()
}

Run go run ./subscribe after go run ./app. It prints houses: 1, then houses: 2 when the result includes Harkonnen. If the first result already includes Harkonnen, it prints only that result.