Baton

Relay, for SwiftUI and Compose.

You write the fields a view needs, next to the view. Baton asks for them in one request, shows the cached data on the first frame, and re-renders only where a field changed. The compiler checks every field against the schema. The UI framework watches the records.

swift package add-dependency https://github.com/shergin/baton --from 0.20.0

Swift 6.2 · Kotlin 2.4 · the platform's own frameworks and SQLite, nothing vendored · one compiler, already built

Start here New to GraphQL? One screen, end to end Open the playground

IssueRow.swift

import Baton
import SwiftUI

struct IssueRow: View {
    @Fragment("""
    fragment IssueRow_issue on Issue {
      number
      title
      author { login }
    }
    """)
    var issue: IssueRow_issue

    var body: some View {
        VStack(alignment: .leading) {
            Text("#\(issue.number) \(issue.title)")
            Text(issue.author?.login ?? "ghost")
                .foregroundStyle(.secondary)
        }
    }
}
Plate 1. A row names the fields it reads, right beside its body. It cannot read anything else. SwiftUI on one tab, Compose on the other. Same document, same lens.

A field changes. One view re-renders.#

The store below is a real response from the Rick and Morty API. The screen beside it reads those records through the fragments the compiler reported. There is no view model in between. Click a field. Watch who wakes up.

CharactersQuery
Rick SanchezAlive · Human
CharactersScreen
Morty SmithAlive · Human
CharactersScreen
Summer SmithAlive · Human
CharactersScreen
Beth SmithAlive · Human
CharactersScreen
Jerry SmithAlive · Human
CharactersScreen
Abadango Cluster PrincessAlive · Alien
CharactersScreen

The store click a field to change it

client:rootQuery
characters(page:1)
client:root:characters(page:1)Characters
results
Character:1Character
id
image
name
species
status
Character:2Character
id
image
name
species
status
Character:3Character
id
image
name
species
status
Character:4Character
id
image
name
species
status
Character:5Character
id
image
name
species
status
Character:6Character
id
image
name
species
status

0 of bodies re-ran

Nothing has changed yet.

Plate 2. The list reads the root's link and the list's links. Each row reads the four fields its fragment declared, on its own record. A refetch that comes back with the same bytes notifies nobody. The store compares before it tells anyone.

The view never sees the data layer

No query file to keep in sync. No cache-update function. No view model copying fields into a struct. The fragment sits next to the body, and the data is there. A parent hands a child a lens, not a bag of fields. The child reads exactly what it asked for.

Every claim can be checked

Read a field through a lens and you get the same value as the raw response, at the same path. Fixtures under spec/ prove it for Swift and for Kotlin. A speed claim has a bench in the repository. If a view re-rendered, a field it read changed, and a test can count that.

Relay's language, native's mechanisms

The directives, the conventions, and the compiler's front end are Relay's. A web team and a native team can use the same words. Relay built a runtime because React cannot see which view read which field. SwiftUI's Observation and Compose's snapshot state can. Baton uses those, and leaves Relay's read side out.

The shape of a screen#

A screen is one query, and each view on it is one fragment. The compiler builds the query from the fragments spread into it, so nobody writes the screen's request by hand.

IssuesScreen.swift

import Baton
import SwiftUI

struct IssuesScreen: View {
    @Query("""
    query IssuesQuery($owner: String!, $name: String!) {
      repository(owner: $owner, name: $name) {
        nameWithOwner
        issues(first: 20, states: OPEN) {
          nodes { id ...IssueRow_issue }
        }
      }
    }
    """)
    var issues: IssuesQuery

    var body: some View {
        switch issues.phase {
        case .ready(let data):
            if let repo = data.repository {
                List {
                    ForEach(repo.issues.nodes ?? .empty) {
                        IssueRow(issue: $0.issueRow)
                    }
                }
                .navigationTitle(repo.nameWithOwner)
            }
        case .loading:
            ProgressView()
        case .failed(let error):
            ErrorView(error) { issues.retry() }
        }
    }
}
Plate 3. The screen names the repository with its variables, and spreads the row's fragment into the open issues. The row's accessor, issueRow, is the baton. The parent hands it over, and cannot read through it.
query
IssuesQuery
variables
$owner: String! $name: String!
spreads
IssueRow_issue
sent as
d8e7121ec0e10dfd0dd7c8d126e75dd1, the text's hash; the text stays on the server
the text
query IssuesQuery($owner:String!,$name:String!){repository(owner:$owner,name:$name){nameWithOwner,issues(first:20,states:OPEN){nodes{id,...IssueRow_issue}},id}}fragment IssueRow_issue on Issue{number,title,author{__typename,login,...on Node{__isNode:__typename,id}}}
Plate 4. What the compiler sends: the operation, then the fragment it reaches, with the id fields identity needs added. The whole text is one line, hashed to an id. Under persistConfig the request carries that id and nothing else.

The lens of IssueRow_issue, a fragment, reads a record of type Issue:

accessorreadsas
numbernumbera scalar
titletitlea scalar
authorauthora lens of Actor, optional
  loginlogina scalar
Plate 5. The row's lens, as the compiler reported it: one accessor per field the fragment declared, and no accessor for anything else. Masking is not a house rule. It is the shape of the type.

Records, not models

A response is decoded straight into records, keyed by type and id, off the main actor. There is no model tree in between. The list, the detail, and the cast of an episode all read the one record a character is. The store shows a response beside the records it became.

Lists that page in the store

A list is a Relay connection on a refetchable fragment. The lens pages with loadNext, the store merges the pages, and a mutation adds an edge with a directive rather than a cache updater. Lists walks the fixture that proves it.

Writes you can see at once

A mutation is an action. Its optimistic response is a typed value. It goes through the same ingest as a server's answer, shows up in the turn of the call, and comes back off if the server says no. Writes steps through a layer applied, resolved, and reverted.

Honest data

Nullability is what the schema says. @required moves a null up to where the product wants to deal with it, and @catch turns a field error into a Result. A field error survives caching. Missing data is reported and healed, never invented. Honest data has the directives.

The first frame has the data

Reads are synchronous on the main actor, so a handle resolves against the store before the first body runs. After a launch, the store reads what the handle needs from its image on disk, and a screen the app has seen does not flash a spinner. The walkthrough follows one screen through to the next launch.

The compiler decides

Every operation is known at build time. Identity, aggregation, masking, storage keys, persisted ids, and diagnostics are settled before the app runs. A wrong field is a build error, pointing at the character in the GraphQL text. The compiler shows one.

Twelve words#

Twelve words, and that is the whole vocabulary. A feature is some combination of these, or a Relay directive the compiler already understands, or it does not ship.

  • schemathe server's menu, checked in and compiled in
  • documenta query, a mutation, a subscription, or a fragment, beside a view
  • directivethe only way behaviour attaches to data
  • lensa typed window onto one record, read-only
  • recordan observable object, keyed by type and id
  • storeall the records, owned by the main thread
  • planhow a response becomes records, decided by the compiler
  • operation valuean operation's variables, the thing a parent constructs
  • connectiona list that pages, merged in the store
  • environmentthe session: one store, one transport
  • transportone verb, send, yielding payloads
  • phaseloading, ready, or failed, and always readable

Where to go#

Start here

  • Getting startedInstall, the schema, the first screen, the first fragment, the first list.
  • GraphQL for mobile engineersThe menu, the order, the response in the order's shape, ids, lists, writes. No GraphQL required.
  • One screen, end to endFrom the fragment beside a view to the frame, the records, the one re-render, and the next launch.
  • PlaygroundType a fragment. Read what the compiler wrote.

The guide

  • The twelve wordsThe closed vocabulary, one plate each.
  • ReadsQueries, fragments, lenses, phases, fetch policies.
  • The storeRecords, identity, observation, roots, the image on disk.
  • ListsConnections, pages merged, edge directives.
  • WritesActions, optimistic responses, payloads.
  • Honest dataNulls, errors, missing data, enums, scalars.
  • Live dataSubscriptions, deferred fragments, streamed lists.
  • The compilerWhat it checks, what it writes, how the build runs it.
  • The environmentThe transport, the session, the log, tests.
  • ComposeThe same screens in Kotlin.

Recipes and examples

  • AgentsThe page a coding agent reads first.
  • Every recipeTesting, the exchange, UIKit, view models, porting from Relay, the build integrations.
  • The galleryEvery sample, and what the compiler found in it.

Why it is shaped this way

  • VisionThree commitments and five rules.
  • The principlesEight constraints. Each one names the failure it avoids.
  • DecisionsEvery choice, the evidence, and what would reopen it.
  • Faster, by skipping stepsThree things Apollo does on every response, or every read, that Baton never does.
  • ArticlesThe long version: Relay without the read side, what Meta built, why it is fast, the first frame, two runtimes, the compiler, the honest store, twelve words, Baton beside fate, the small lies a client tells, and how the library is built.

Reference

Faster, by skipping steps#

Baton is faster than Apollo iOS and Apollo Kotlin on the same data, and the store is not the trick: the stores write at about the same speed. Apollo takes three steps, on every response or every read, that Baton does not take at all.

No model tree

Apollo builds a model of the operation from the response's bytes, and builds it again from the store on every read. Baton decodes the bytes straight into record slots, by the plan the compiler emitted. A view reads a slot.

No re-execution

When any field a query read changes, Apollo re-executes the whole query and rebuilds the tree. Baton notifies the slot that changed. Only the bodies that read it run.

No waiting

Apollo's store reads are asynchronous, so a warm cache still shows a loading frame. Baton's reads are synchronous on the main actor. The first body has the data. After a launch, the image on disk has it too.

Each of those is work a view never asked for. How much of a frame it costs depends on the device and the data, so the head-to-heads stay in the repository, in BENCHMARKS.md. Each one has its revision, machine, OS, and date. docs/comparison.md is the longer argument, including the places Apollo is ahead.

The name#

In a relay race, the baton is the thing that actually gets handed over. Here it is the data a screen hands each view: exactly what that view asked for, and nothing else. In Russian the same word, батон, is a loaf of bread. That is why the logo is a loaf, and why every release is named for one.