The guide
Live data
Subscriptions, deferred fragments, and streamed lists. What the handle does when the connection drops, or the app sleeps.
Data can arrive in three ways after the first response. A subscription is a stream of events the server pushes. A deferred fragment is a part of a response the server sends later. A streamed list is a list whose items the server sends one by one. All three go through the same door as a query's response, into the same records. A view that reads a record it names updates as it would after any commit.
A subscription is a stream of events into the store#
A subscription is the third kind of operation. You declare it like a query, and you resolve it in a view. Its handle stays open while the view lives, and it closes when the view goes. Each event is a payload in the operation's shape, normalized at the subscription root and committed. An edge directive on the event's payload appends it to a connection, so a live list grows without a refetch.
CharacterNotes.swift
import Baton
import SwiftUI
struct CharacterNotes: View {
@Fragment("""
fragment CharacterNotes_character on Character
@refetchable(queryName: "CharacterNotesPaginationQuery")
@argumentDefinitions(count: {type: "Int", defaultValue: 10}, cursor: {type: "String"}) {
id
notes(first: $count, after: $cursor) @connection(key: "CharacterNotes_notes") {
edges { node { id text } }
}
}
""")
var character: CharacterNotes_character
@Subscription("""
subscription NoteAdded($characterId: ID!, $connections: [ID!]!) {
noteAdded(characterId: $characterId) {
noteEdge @appendEdge(connections: $connections) {
node { id text }
}
}
}
""")
var noteAdded: NoteAdded
init(character: CharacterNotes_character) {
self.character = character
noteAdded = NoteAdded(characterId: character.id ?? "", connections: [character.notes.connectionID])
}
var body: some View {
ForEach(character.notes.nodes) { note in
Text(note.text ?? "")
}
}
}CharacterNotes.kt
package app
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import baton.Fragment
import baton.Phase
import baton.Query
import baton.Subscription
import baton.rememberQuery
import baton.rememberSubscription
@Fragment($$"""
fragment CharacterNotes_character on Character
@refetchable(queryName: "CharacterNotesPaginationQuery")
@argumentDefinitions(count: {type: "Int", defaultValue: 10}, cursor: {type: "String"}) {
id
notes(first: $count, after: $cursor) @connection(key: "CharacterNotes_notes") {
edges { node { id text } }
}
}
""")
@Subscription($$"""
subscription NoteAdded($characterId: ID!, $connections: [ID!]!) {
noteAdded(characterId: $characterId) {
noteEdge @appendEdge(connections: $connections) {
node { id text }
}
}
}
""")
@Composable
fun CharacterNotes(character: CharacterNotes_character) {
rememberSubscription(NoteAdded(characterId = character.id.orEmpty(), connections = listOf(character.notes.connectionID)))
Column {
for (note in character.notes.nodes) {
Text(note.text.orEmpty())
}
}
}- subscription
NoteAdded- variables
$characterId: ID!$connections: [ID!]!- the text
subscription NoteAdded($characterId:ID!){noteAdded(characterId:$characterId){noteEdge{node{id,text}}}}
The stream as a value#
The handle reads the stream as a value, and you never await it. idle means parked while the app is inactive. connecting lasts until the first event, and then the stream is open. waiting means it will reconnect after a failure, by a fixed backoff: a step that doubles from one second to thirty, jittered, and reset by an event. ended means the server completed, or a request error the server would repeat, or the environment ended. resumptions counts the reopenings, because events may have been missed across each one. An owner that cares observes it and refetches its baseline. retry() opens a waiting or ended stream at once.
A view attaches a handle for TestNoteAdded(characterId: "1", connections: []) under storeOrNetwork, named live; the fetch stays in flight.
Stream {"handle":"live","stream":"connecting","events":0,"resumptions":0}
The stream of live delivers tests/note-added-1.json.
tests/note-added-1.json
{
"data": {
"noteAdded": {
"noteEdge": {
"cursor": "c6",
"node": {
"__typename": "Note",
"id": "n6",
"text": "Live from the garage"
}
}
}
}
}Stream {"handle":"live","stream":"open","events":1}
The store after the step, tests/note-added-1.store.json
| id | "n6" |
|---|---|
| text | "Live from the garage" |
| noteAdded(characterId:"1") | client:root:subscription:noteAdded(characterId:"1") |
|---|
| noteEdge | client:root:subscription:noteAdded(characterId:"1"):noteEdge |
|---|
| cursor | "c6" |
|---|---|
| node | Note:n6 |
The stream of live delivers tests/not-authorized.json.
tests/not-authorized.json
{
"data": null,
"errors": [
{
"message": "not authorized"
}
]
}Stream {"handle":"live","stream":"open","events":1}
The store after the step, tests/note-added-1.store.json
| id | "n6" |
|---|---|
| text | "Live from the garage" |
| noteAdded(characterId:"1") | client:root:subscription:noteAdded(characterId:"1") |
|---|
| noteEdge | client:root:subscription:noteAdded(characterId:"1"):noteEdge |
|---|
| cursor | "c6" |
|---|---|
| node | Note:n6 |
The app becomes inactive.
Stream {"handle":"live","stream":"idle","events":1,"resumptions":0}
The app becomes active.
Stream {"handle":"live","stream":"connecting","events":1,"resumptions":1}
The stream of live delivers tests/note-added-2.json.
tests/note-added-2.json
{
"data": {
"noteAdded": {
"noteEdge": {
"cursor": "c7",
"node": {
"__typename": "Note",
"id": "n7",
"text": "Second live note"
}
}
}
}
}Stream {"handle":"live","stream":"open","events":2,"resumptions":1}
A view attaches a handle for TestNoteAdded(characterId: "2", connections: []) under storeOrNetwork, named other; the fetch stays in flight.
Stream {"handle":"other","stream":"connecting","events":0}
The stream of other delivers tests/note-added-1.json.
tests/note-added-1.json
{
"data": {
"noteAdded": {
"noteEdge": {
"cursor": "c6",
"node": {
"__typename": "Note",
"id": "n6",
"text": "Live from the garage"
}
}
}
}
}Stream {"handle":"other","stream":"open","events":1}
The subscription other is completed by the server.
Stream {"handle":"other","stream":{"ended":null},"events":1,"resumptions":0}
The stream of live fails with a transport failure.
Stream {"handle":"live","stream":"waiting","events":2,"resumptions":1}
The environment's active flag is yours to set, from the scene phase in Swift and from the process lifecycle on Android. While the flag is false, every retained subscription is parked. A revalidate() on the return refetches what went stale meanwhile. The Android sample's Activation and the UIKit recipe's lifecycle section are the two spellings.
The transport underneath#
Subscriptions travel through the environment's subscription transport, which is any transport with the one verb. The socket transport speaks graphql-transport-ws. The HTTP transport reads text/event-stream for graphql-sse, in its distinct-connections mode, so a server that streams over HTTP needs no socket at all. On Android the platform has no WebSocket client, so the socket is the app's own, through the baton-okhttp edge or any client that implements the protocol's few calls.
Environment(
transport: URLSessionTransport(url: api, credentials: credentials),
subscriptions: GraphQLTransportWebSocket(url: socket, credentials: credentials)
)Environment(
HttpTransport(api, credentials = credentials),
subscriptions = GraphQLTransportWebSocket(socket, client = OkHttpWebSocketClient(okHttp), credentials = credentials),
)A part that arrives later: @defer#
A spread marked @defer is a part the server may deliver later, in the same response. The spread's accessor is optional, and it is nil until the fragment's fields are present. The rest of the operation renders meanwhile. The availability check does not wait for the deferred part. A part the store holds only half of is cleared and fetched, rather than read as empty.
CharacterScreen.swift
import Baton
import SwiftUI
struct CharacterScreen: View {
@Query("""
query CharacterQuery($id: ID!) {
character(id: $id) {
name
...CharacterNotes_character @defer
}
}
""")
var character: CharacterQuery
var body: some View {
if case .ready(let data) = character.phase, let character = data.character {
Text(character.name ?? "Unknown").font(.largeTitle)
if let notes = character.characterNotes {
CharacterNotes(character: notes)
} else {
ProgressView()
}
}
}
}CharacterScreen.kt
package app
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import baton.Fragment
import baton.Phase
import baton.Query
import baton.Subscription
import baton.rememberQuery
import baton.rememberSubscription
@Query($$"""
query CharacterQuery($id: ID!) {
character(id: $id) {
name
...CharacterNotes_character @defer
}
}
""")
@Composable
fun CharacterScreen(id: String) {
val query = rememberQuery(CharacterQuery(id = id))
val phase = query.phase
if (phase is Phase.Ready) phase.data.character?.let { character ->
Text(character.name ?: "Unknown")
val notes = character.characterNotes
if (notes != null) CharacterNotes(notes) else CircularProgressIndicator()
}
}The built-in HTTP transport reads multipart/mixed for the parts, and the environment assembles each part at the record its path names. A deferred part addressed to a place the store does not have is dropped and logged, and never applied somewhere else.
A list that grows: @stream#
A plural field marked @stream(initialCount:) arrives with its first items. The server sends the rest one or a few at a time, in the same response. Each item lands at its index in the list, keyed as it would have been had it come with the first part, so a view that reads the list sees it grow in place. The directive adds no accessor on the list. The handle's fetch stays in flight while the stream runs, so isRefreshing says whether more is to come. A connection marked @stream_connection(key:, initial_count:) streams its edges and defers its page info, as Relay rewrites it. Each edge merges into the connection as it lands.
EpisodeList.swift
import Baton
import SwiftUI
struct EpisodeList: View {
@Query("""
query EpisodesQuery($id: ID!) {
character(id: $id) {
name
episode @stream(label: "episodes", initialCount: 3) { id name }
}
}
""")
var episodes: EpisodesQuery
var body: some View {
if case .ready(let data) = episodes.phase, let character = data.character {
List {
ForEach(character.episode) { episode in
Text(episode.name ?? "Untitled")
}
if episodes.isRefreshing {
ProgressView()
}
}
}
}
}EpisodeList.kt
package app
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import baton.Phase
import baton.Query
import baton.rememberQuery
@Query($$"""
query EpisodesQuery($id: ID!) {
character(id: $id) {
name
episode @stream(label: "episodes", initialCount: 3) { id name }
}
}
""")
@Composable
fun EpisodeList(id: String) {
val query = rememberQuery(EpisodesQuery(id = id))
val phase = query.phase
if (phase is Phase.Ready) phase.data.character?.let { character ->
LazyColumn {
items(character.episode, key = { it.recordID.key }) { episode -> Text(episode.name ?: "Untitled") }
if (query.isRefreshing) item { CircularProgressIndicator() }
}
}
}A view attaches a handle for TestStreamedEpisodes(id: "1") under storeOrNetwork, named rick; the transport answers its fetch with tests/character-streamed-1.json.
tests/character-streamed-1.json
{
"data": {
"character": {
"id": "1",
"name": "Rick Sanchez",
"episode": [
{
"id": "1",
"name": "Pilot"
}
]
}
},
"hasNext": true
}Phase {"handle":"rick","phase":"ready","isRefreshing":true}
Fetch {"handle":"rick","fetch":"inFlight"}
| A lens reads | and finds |
|---|---|
rick · character.episode.0.name | Pilot |
The fetch of rick is answered with tests/character-streamed-3-first.json.
tests/character-streamed-3-first.json
{
"data": {
"id": "3",
"name": "Anatomy Park"
},
"path": [
"character",
"episode",
2
],
"label": "TestStreamedEpisodes$stream$episodes",
"hasNext": true
}Fetch {"handle":"rick","fetch":"inFlight"}
| A lens reads | and finds |
|---|---|
rick · character.episode.0.name | Pilot |
rick · character.episode.1.name | Anatomy Park the item at index 1 has not arrived; a list reads past a null element |
The store after the step, tests/character-streamed-hole.store.json
| id | "1" |
|---|---|
| name | "Pilot" |
| id | "3" |
|---|---|
| name | "Anatomy Park" |
| character(id:"1") | Character:1 |
|---|
The fetch of rick is answered with tests/character-streamed-2.json.
tests/character-streamed-2.json
{
"data": {
"id": "2",
"name": "Lawnmower Dog"
},
"path": [
"character",
"episode",
1
],
"label": "TestStreamedEpisodes$stream$episodes",
"hasNext": true
}Notified Character:1.episode
| A lens reads | and finds |
|---|---|
rick · character.episode.1.name | Lawnmower Dog |
rick · character.episode.2.name | Anatomy Park |
The fetch of rick is answered with tests/character-streamed-end.json.
tests/character-streamed-end.json
{
"hasNext": false
}Phase {"handle":"rick","phase":"ready","isRefreshing":false,"isStale":false}
Fetch {"handle":"rick","fetch":"idle"}
The store after the step, tests/character-streamed.store.json
| id | "1" |
|---|---|
| name | "Pilot" |
| id | "2" |
|---|---|
| name | "Lawnmower Dog" |
| id | "3" |
|---|---|
| name | "Anatomy Park" |
| character(id:"1") | Character:1 |
|---|
An item is dropped and logged when another commit has changed its list since the stream left it, as Relay's executor drops it. A mutation that replaced the list meanwhile is not overwritten by a stale order. A stream the transport ends before the part that says it is the last fails the fetch. Nothing dates the operation's root, so the next attach fetches the list whole.
What a view does not do#
A view never awaits an event, never holds a socket, and never merges a stream into its own state. It reads the record the event changed, the way it reads any record, and it reads the stream's state when it wants to show a dot. The tests drive a subscription by hand with ScriptedTransport, delivering, completing, or failing events. Previews and tests shows how.
Baton