Tutorials

Application recipes: pages, cache and offline edits

Run complete pagination, TTL cache and offline sync programs, including failures and ownership.

v1.2.2Beginnerark_data_layer

Русская версия

These examples answer practical questions that Repository<Data> deliberately does not decide for you: which page to request, when a cached profile expires, and how to save an edit without a network connection. They use the existing public API, not new built-in pagination or synchronization features.

Start with the basic example if the DataSource → Repository → subscriber boundary is new to you. Then choose one complete program below. You do not need Flutter, DI, a server or a database.

Run and read the examples

Run these commands from the package root:

sh
dart pub get
dart run example/recipes/pagination_recipe.dart
dart run example/recipes/ttl_cache_recipe.dart
dart run example/recipes/offline_sync_recipe.dart

Each program executes the normal path and its failure scenarios. It prints PASS lines only after checking actual state; a failed check throws and the process exits unsuccessfully. The programs produce 5, 5 and 9 lines respectively. They do not depend on assertions being enabled. Run all three through the package test suite with:

sh
dart test test/recipe_examples_test.dart

Each file has the same reading order:

  1. main() calls the recipe's run() method.
  2. run() creates sources, calls the Repository, checks outcomes and cleans up.
  3. The concrete Repository below implements the application policy.
  4. Small immutable domain objects and typed source contracts follow it.
  5. The in-memory source at the bottom makes failures and timing reproducible.

The helpers are private so each file runs independently with only a public package import. In an application, put your domain contract, data implementation and source adapters into their usual separate files. The recipe wrapper is a demonstration, not a new application framework to inherit from.

1. Load a catalog one page at a time

Full program: pagination_recipe.dart. Useful for a catalog or search result whose next request uses an opaque cursor.

Follow the first request

  1. _CatalogRepository starts with an empty immutable list and hasLoaded: false. A null cursor before the first request means “start”, not “end”.
  2. loadNext() asks the typed _CatalogSource for that page. If another caller invokes loadNext() before completion, it receives the same Future. It does not send a duplicate request or accidentally start the following page.
  3. _ProductRecord is a source DTO. _Product.from trims and validates its ID and display name. Consumers receive _Product, not the raw response DTO.
  4. The Repository validates the whole response, merges products by business ID, then calls setData once. An updated duplicate keeps its original position.
  5. After a successful page, a null next cursor means the end. Further calls do nothing; they do not start the list again.

The example subscribes before loading. After close, it checks exactly three delivered states: initial replay and two successful pages. The failed request neither commits data nor advances commitRevision.

What happens when a page fails?

The caller receives _CatalogUnavailable through loadNext(). Existing products and the cursor stay unchanged. Calling loadNext() again retries the same page. Loading/error indicators can be handled by your state manager; this example does not insert presentation flags into the product list.

Blank identifiers, blank cursors and a cursor that revisits an earlier page are rejected before commit. Cursors are otherwise opaque: they are not trimmed, parsed as integers, or exposed as arbitrary request maps.

What this policy does not cover

There is no simultaneous refresh, filter replacement or independent page cache. This is one ordered cursor chain; adding those operations requires defining how they invalidate an older chain. The accumulated list and cursor set grow with pages. Add an application-specific window if retaining the full catalog is too expensive. Duplicate merging here is not a promise that a changing remote catalog is a consistent snapshot: that guarantee must come from the source API.

2. Read a profile with a TTL cache

Full program: ttl_cache_recipe.dart. Useful when a previously fetched profile should open quickly but eventually refresh. _ProfileCache and _ProfileRemote are separate typed contracts.

Decide freshness explicitly

The constructor receives a user ID, a positive TTL and a clock function. A value is fresh when its age is nonnegative and less than the TTL. At exactly five minutes, the five-minute example cache is stale. A future timestamp after a clock change is not treated as proof of freshness. No real timer or waiting is needed to demonstrate expiry: the example advances its injected clock.

Follow load()

  1. Read the cache for the requested user. A record for another user is an adapter error, not permission to display that user's profile. Blank fields are also rejected before publication.
  2. Publish a fresh cached value and return without accessing the remote source.
  3. If the value is stale, publish it with isStale: true, then request a refresh. The view can keep usable content visible while the caller awaits load().
  4. Normalize the remote record and publish fresh domain data.
  5. Write that record and its fetch timestamp to the cache.

Concurrent calls share the whole load operation, including cache access. The domain snapshot reports whether data came from empty, cache, remote or memory; it does not expose the source DTO or the source instances.

There are two different failures

  • Network failure: load() fails and the stale profile remains available. The caller decides when to retry or how to present the error.
  • Cache write failure after a successful response: load() still reports the write error, but the fresh profile remains in memory. Losing persistence is not the same as failing to obtain usable data. A later load prefers this unpersisted fresh value over an older cache record; it does not roll the profile back. Once that in-memory value expires, the next successful refresh attempts persistence again. It is not a separate immediate “retry cache write” API.

This policy is a deliberate trade-off. An application that must guarantee an offline copy before displaying new data should persist first, then publish, as the next example does. Cache read failures propagate rather than silently becoming misses. The example does not add background retries, cross-account cache invalidation, encryption, eviction or a general caching service to the package.

3. Save a note offline, then synchronize it

Full program: offline_sync_recipe.dart. This example edits one existing nonempty text note. It demonstrates both offline-first storage and explicit synchronization, not creation/deletion of a collection or a universal merge engine.

Part A: save locally before publishing

  1. load() reads the local note and its pending edits. Before load, data is null; editing or synchronization is rejected until local data has been loaded.
  2. save(text) validates the text and increments the local revision.
  3. One _NoteStore.update atomically stores the new note and an outbox entry. The entry contains the text, local revision and stable idempotency key.
  4. Only after local storage succeeds does the Repository publish _NoteData. The snapshot contains the current text, local/server revisions, pending count and a conflict indicator. Consumers never receive the mutable outbox itself.
  5. If local writing fails, neither data nor outbox changes and nothing is published. No network request is needed to save successfully.

The program closes and recreates the Repository over the same store and checks that the note and pending work are restored. That proves rehydration from the adapter, not persistence across a real process restart.

Part B: send and acknowledge one edit

  1. synchronize() captures the current local revision as its batch boundary. Await your save() before invoking sync if that edit must join this batch.
  2. The oldest pending edit receives an expected server version. This exact request is saved locally before network access, so a retry cannot change its key, payload or expected version after an ambiguous failure.
  3. The server checks the idempotency key and original payload. A repeat returns the prior receipt. Reusing the key with another payload is a protocol error. For a new key, the server checks the expected version before changing the note.
  4. The acknowledgement atomically removes only that edit and advances the locally known server version. It does not replace the latest local text with an older response. Local edits made during the network call remain queued.
  5. The next queued edit uses the acknowledged version. Edits newer than the batch boundary wait for the next explicit sync. There is no hidden retry worker.

Local read/modify/write/publication work is serialized inside the Repository; the network call is outside that queue. Consequently, saving a new local edit is not blocked behind a slow server request. Concurrent sync callers share a Future. Use one active Repository coordinator for this note; this is not an inter-isolate or multi-process lock.

Why the failure paths matter

  • No network: keep the prepared outbox entry and retry later.
  • Server applied the edit but its response was lost: keep the same entry. A recreated Repository retries it and receives the prior receipt without applying the edit twice.
  • Client could not save the acknowledgement: local work still remains queued. The same idempotent retry recovers the receipt without repeating the write.
  • Another device changed the server version: report _VersionConflict, keep local work and the remote version unchanged, and expose hasConflict. Do not silently discard a draft, overwrite the server or rebase an ambiguous request. Conflict resolution is a separate application action: obtain the authoritative remote note, ask the user to keep/merge/discard, and atomically record the chosen baseline and new operation. This example deliberately does not choose for them.

The conflict indicator is session state: recreating the Repository reloads the outbox, not a persisted conflict flag. A repeat sync rechecks the server version. The saved expected version still protects against an unintended overwrite.

What real adapters must guarantee

The in-memory store updates synchronously in one isolate. A real database adapter must provide an atomic transaction covering local data, revision counters, prepared request and outbox. A real server must commit the note change and its idempotency receipt atomically, scope keys by authenticated identity/resource, validate the entire payload, and retain receipts for its documented retry period. The fixed demo client ID is not a production identifier: persist a unique client ID and monotonic revision counter; do not reuse them for a fresh store.

The example makes no claim of exactly-once network delivery, durable storage, bounded outbox growth, encryption, authentication or background execution. These are adapter/application requirements, not features of Repository<Data>.

Closing and ownership in all recipes

Sources are constructed by the composition scope and resolved once through DataSourceContainer. Repositories never close those borrowed sources.

Closing invalidates later publication, not the underlying external operation. A network write may still take effect after the Repository closes. The sync example leaves the request in the outbox so the next coordinator can recover its receipt. A local transaction already in progress may still complete; queued work that has not started is rejected after close. Await outstanding operation Futures and handle their errors before closing the sources that serve them.

The pagination subscriber remains unpaused through close() to receive all committed states and done. In error cleanup it cancels its own subscription first. Do not infer that every foreign/paused subscription can always be drained by a deadline: see stream and lifecycle.

For additional subscription assertions, the published ark_data_layer_test companion observes a Repository without taking ownership. The examples here deliberately use only the runtime package and standard Dart libraries.