> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream in tempo reale

> Iscriviti agli eventi live dell'applicazione tramite uno stream Server-Sent Events (SSE).

`api.ApplicationRealtime(appID)` apre uno stream [Server-Sent Events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) e restituisce un `*rest.RealtimeStream`. Iteralo con `stream.Next()` fino a `io.EOF`.

```go theme={null}
client := rest.NewClient(os.Getenv("SQUARECLOUD_API_KEY"))
defer client.Close()

api := rest.New(client)
```

## Consumare lo stream

```go theme={null}
stream, err := api.ApplicationRealtime("abc123def456abc123def456")
if err != nil {
	panic(err)
}
defer stream.Close()

for {
	event, err := stream.Next()
	if err == io.EOF {
		break // stream ended (e.g. 10-minute TTL reached)
	}
	if err != nil {
		panic(err)
	}

	fmt.Println(event.Name, string(event.Data))
}
```

Usa sempre `defer stream.Close()` — uno stream non chiuso tiene occupato uno degli slot di connessione del tuo account.

## Forma degli eventi

Lo stream emette due tipi di frame:

* **Eventi di sistema** — messaggi del ciclo di vita della connessione: `REALTIME_CONNECTING`, `REALTIME_TIMEOUT`, `REALTIME_DISCONNECTED`, `REALTIME_RECONNECT` e `REALTIME_ERROR`.
* **Eventi `message`** — il payload dell'applicazione. `Data` è opaco per l'SDK, di solito JSON — deserializzalo tu stesso:

```go theme={null}
if event.Name == "message" {
	var payload map[string]any
	if err := json.Unmarshal(event.Data, &payload); err == nil {
		fmt.Println(payload)
	}
}
```

## Limiti di connessione

<Warning>
  Un singolo account può tenere aperte al massimo **5 connessioni simultanee**, e ogni connessione dura fino a **10 minuti** (il suo TTL). Al raggiungimento del TTL lo stream termina con `io.EOF` — riconnettiti in un loop per restare iscritto.
</Warning>

```go theme={null}
for {
	stream, err := api.ApplicationRealtime("abc123def456abc123def456")
	if err != nil {
		panic(err)
	}

	for {
		event, err := stream.Next()
		if err != nil {
			break // io.EOF on TTL — reconnect
		}
		fmt.Println(event.Name, string(event.Data))
	}

	stream.Close()
}
```

## Cancellazione

Allega un `context.Context` con `rest.WithContext` per fermare lo stream dall'esterno:

```go theme={null}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

stream, err := api.ApplicationRealtime("abc123def456abc123def456", rest.WithContext(ctx))
if err != nil {
	panic(err)
}
defer stream.Close()

// cancel() from another goroutine ends the stream
```
