›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Architecture Patterns in Practice

Screen and App Architecture: MVVM, Unidirectional Data Flow and Offline-First, with Runnable Code

October 3, 2026 · 25 min read

Software Architecture, Design Patterns, C#, Python, Swift, Kotlin, MVVM, Mobile, Offline-First

This post is part of Architecture Patterns in Practice, a series that puts runnable code behind the patterns in my architecture patterns map for 2026. The first post organized a backend. This one moves to the client and asks how a screen should hold its state, and what happens to that state when the network goes away.

If you build for iOS, Android, .NET MAUI or the web, you're already using some version of these three. MVVM separates what a screen shows from how it's drawn. Unidirectional data flow makes every state change go through one door. Offline-first makes the local database, not the server, the thing the UI reads from. They layer on top of each other: an offline-first repository feeds a view model, and the view model exposes its state in one direction.

PatternThe question it answersGoF idea underneath
MVVMWhere does screen state and logic live, if not in the view?Observer (bindings) + Command (actions)
Unidirectional data flowHow does state change without turning into spaghetti?Command (actions) + Memento (immutable snapshots)
Offline-firstWhat does the app do when the network isn't there?Proxy (the repository) + a queue of Commands (the outbox)

Every snippet runs as is, with no packages: C# as .NET 10 file-based apps (dotnet run file.cs), Python with the standard library, Swift with swift file.swift, and Kotlin with kotlinc -script file.kts.

MVVM

The problem. The view does too much. A button handler validates input, calls the network, sets a spinner, catches errors and updates a list. All of that logic is tied to UI types, so the only way to test it is to launch the app and tap. When the design changes, the logic gets rewritten with it.

The pattern. Split the screen into three parts. The model is your data and business logic. The view model holds the screen's state (the query, whether it's loading, the results, a message) and exposes commands for user actions. The view binds to the view model and redraws when it's told something changed. Microsoft's MAUI guide puts the rule simply: the view knows about the view model, the view model knows about the model, and never the other way round. The view model has no UI types in it, so you can test it in a plain console app.

Here's a search screen's view model in C#, with the "view" played by a console listener that prints what a real UI would redraw:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

var vm = new SearchViewModel(new FakeRecipeService());

// The "view": in MAUI or WPF this is XAML bindings. Here it just prints what it would redraw.
vm.PropertyChanged += (_, e) => Console.WriteLine($"  view redraws {e.PropertyName}: {Describe(vm, e.PropertyName)}");

Console.WriteLine($"can search? {vm.SearchCommand.CanExecute(null)}");
vm.Query = "so";
Console.WriteLine($"can search? {vm.SearchCommand.CanExecute(null)}");
await vm.SearchAsync();
vm.Query = "xyz";
await vm.SearchAsync();

static string Describe(SearchViewModel vm, string? name) => name switch
{
    nameof(vm.Query) => vm.Query,
    nameof(vm.IsLoading) => vm.IsLoading.ToString(),
    nameof(vm.Results) => $"[{string.Join(", ", vm.Results)}]",
    nameof(vm.Message) => vm.Message,
    _ => "?"
};

interface IRecipeService { Task<IReadOnlyList<string>> SearchAsync(string query); }

sealed class FakeRecipeService : IRecipeService
{
    private static readonly string[] All = ["Soup", "Sourdough", "Sorbet", "Pasta"];
    public async Task<IReadOnlyList<string>> SearchAsync(string query)
    {
        await Task.Delay(10);  // pretend network
        return All.Where(r => r.StartsWith(query, StringComparison.OrdinalIgnoreCase)).ToList();
    }
}

// The view model: screen state + commands. No UI types, so it's testable in a console app.
sealed class SearchViewModel(IRecipeService recipes) : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    private string _query = "";
    private bool _isLoading;
    private IReadOnlyList<string> _results = [];
    private string _message = "";

    public string Query { get => _query; set { if (Set(ref _query, value)) _command?.RaiseCanExecuteChanged(); } }
    public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); }
    public IReadOnlyList<string> Results { get => _results; private set => Set(ref _results, value); }
    public string Message { get => _message; private set => Set(ref _message, value); }

    private RelayCommand? _command;
    public ICommand SearchCommand => _command ??= new RelayCommand(async () => await SearchAsync(), () => Query.Length >= 2);

    public async Task SearchAsync()
    {
        IsLoading = true;
        Results = await recipes.SearchAsync(Query);
        Message = Results.Count == 0 ? $"No recipes for '{Query}'" : $"{Results.Count} found";
        IsLoading = false;
    }

    private bool Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        return true;
    }
}

sealed class RelayCommand(Action execute, Func<bool> canExecute) : ICommand
{
    public event EventHandler? CanExecuteChanged;
    public bool CanExecute(object? parameter) => canExecute();
    public void Execute(object? parameter) => execute();
    public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
can search? False
  view redraws Query: so
can search? True
  view redraws IsLoading: True
  view redraws Results: [Soup, Sourdough, Sorbet]
  view redraws Message: 3 found
  view redraws IsLoading: False
  view redraws Query: xyz
  view redraws IsLoading: True
  view redraws Results: []
  view redraws Message: No recipes for 'xyz'
  view redraws IsLoading: False

Look at the order of events in that output. The command is disabled until the query has two characters, the spinner turns on, the results arrive, and the spinner turns off. Every one of those is a fact about state you can assert in a unit test, with no UI involved.

The Set helper and RelayCommand are boilerplate, and in a real app you'd let a library write them. The .NET Community MVVM Toolkit generates both from [ObservableProperty] and [RelayCommand] attributes. I wrote them by hand here so you can see there's no magic.

The Python version uses a descriptor so each property notifies listeners when it changes, which is what INotifyPropertyChanged does by hand:

import asyncio
from typing import Callable


class Observable:
    """A property that tells listeners when it changes (what INotifyPropertyChanged does by hand)."""

    def __set_name__(self, owner, name):
        self.name = "_" + name

    def __get__(self, obj, objtype=None):
        return getattr(obj, self.name)

    def __set__(self, obj, value):
        if getattr(obj, self.name, object()) == value:
            return
        setattr(obj, self.name, value)
        for listener in obj._listeners:
            listener(self.name[1:], value)


class SearchViewModel:
    query = Observable()
    is_loading = Observable()
    results = Observable()
    message = Observable()

    def __init__(self, search: Callable):
        self._listeners: list[Callable] = []
        self._search = search
        self.query, self.is_loading, self.results, self.message = "", False, [], ""

    def bind(self, listener: Callable) -> None:
        self._listeners.append(listener)

    @property
    def can_search(self) -> bool:
        return len(self.query) >= 2

    async def run_search(self) -> None:
        self.is_loading = True
        self.results = await self._search(self.query)
        self.message = f"{len(self.results)} found" if self.results else f"No recipes for {self.query!r}"
        self.is_loading = False


async def fake_search(query: str) -> list[str]:
    await asyncio.sleep(0.01)  # pretend network
    return [r for r in ["Soup", "Sourdough", "Sorbet", "Pasta"] if r.lower().startswith(query.lower())]


async def main():
    vm = SearchViewModel(fake_search)
    vm.bind(lambda name, value: print(f"  view redraws {name}: {value}"))  # the "view"

    print("can search?", vm.can_search)
    vm.query = "so"
    print("can search?", vm.can_search)
    await vm.run_search()

    # The test you get for free: no UI, just state.
    assert vm.results == ["Soup", "Sourdough", "Sorbet"] and not vm.is_loading


asyncio.run(main())
can search? False
  view redraws query: so
can search? True
  view redraws is_loading: True
  view redraws results: ['Soup', 'Sourdough', 'Sorbet']
  view redraws message: 3 found
  view redraws is_loading: False

In SwiftUI the bindings are built into the language. The @Observable macro tracks which properties a view reads, and redraws only when those change:

import Observation

protocol RecipeService { func search(_ query: String) async -> [String] }

struct FakeRecipeService: RecipeService {
    func search(_ query: String) async -> [String] {
        ["Soup", "Sourdough", "Sorbet", "Pasta"].filter { $0.lowercased().hasPrefix(query.lowercased()) }
    }
}

@MainActor @Observable
final class SearchViewModel {
    var query = ""
    private(set) var isLoading = false
    private(set) var results: [String] = []
    private(set) var message = ""

    private let service: RecipeService
    init(service: RecipeService) { self.service = service }

    var canSearch: Bool { query.count >= 2 }

    func search() async {
        isLoading = true
        results = await service.search(query)
        message = results.isEmpty ? "No recipes for '\(query)'" : "\(results.count) found"
        isLoading = false
    }
}

// In SwiftUI the view is just:  List(vm.results, id: \.self) { Text($0) }
// and it re-renders when a property it read changes. Here we drive it directly.
@MainActor func demo() async {
    let vm = SearchViewModel(service: FakeRecipeService())
    print("can search?", vm.canSearch)
    vm.query = "so"
    print("can search?", vm.canSearch)
    await vm.search()
    print(vm.results, vm.message, "loading:", vm.isLoading)
}

await demo()
can search? false
can search? true
["Soup", "Sourdough", "Sorbet"] 3 found loading: false

private(set) is doing real work here. The view can read results but can't assign it, so the only way to change what the screen shows is to go through the view model.

The GoF pattern underneath. Data binding is the Observer pattern: the view subscribes to the view model and gets notified on change. ICommand is the Command pattern: a user action turned into an object with Execute and CanExecute, so a button can enable or disable itself without knowing what the action does. Martin Fowler described the same split in 2004 as the Presentation Model. MVVM is that idea with bindings. Command gets a full treatment in Command, Chain of Responsibility, Mediator and Template Method, and Observer's network-sized version shows up in the messaging post.

When not to use it. A screen with one label and one button doesn't need a view model. SwiftUI and Compose both make simple local state (@State, remember) the easy path for a reason: a toggle that only affects its own view can live in the view. The common MVVM failure is the opposite of the original problem: a single view model per app section that grows to two thousand lines and holds state for five screens. Keep one view model per screen, and push business rules down into the model or a use case, so the view model only shapes data for display.

Unidirectional data flow

The problem. MVVM tells you where state lives, but not how it changes. As a screen grows, the view model gains a dozen public setters. A property change triggers another, which triggers a network call, which sets a third. Two code paths update the same list in different ways, and a bug report says "sometimes the total is wrong" with no way to reproduce it.

The pattern. State flows down, events flow up, and there's one source of truth. The whole screen's state is one immutable value. The UI can't change it. It can only send an action, a plain piece of data describing what happened ("AddItem", "RefreshTapped"). A reducer, a pure function of (state, action), returns the next state. The store holds the current state and notifies the view. Android's architecture guide recommends exactly this shape for the UI layer, and it's the core of Redux, the Elm architecture and Swift's Composable Architecture.

using System.Collections.Immutable;

var store = new Store<CartState, ICartAction>(CartState.Empty, Cart.Reduce);
store.Subscribe(s => Console.WriteLine($"  render: {s}"));   // state flows down

store.Dispatch(new AddItem("Coffee", 4.50m));                  // events flow up
store.Dispatch(new AddItem("Bagel", 3.00m));
store.Dispatch(new ApplyCoupon("TENOFF"));
store.Dispatch(new ApplyCoupon("BOGUS"));
store.Dispatch(new RemoveItem("Bagel"));

Console.WriteLine($"history: {store.History.Count} states, first total {store.History[0].Total}");

// ---- State: one immutable value for the whole screen ----
sealed record CartState(ImmutableList<(string Name, decimal Price)> Items, decimal DiscountPct, string? Error)
{
    public static CartState Empty { get; } = new([], 0, null);
    public decimal Total => Math.Round(Items.Sum(i => i.Price) * (1 - DiscountPct / 100), 2);
    public override string ToString() =>
        $"{Items.Count} items, total {Total}" + (DiscountPct > 0 ? $" (-{DiscountPct}%)" : "") + (Error is null ? "" : $", error: {Error}");
}

// ---- Actions: plain data describing what happened ----
interface ICartAction;
sealed record AddItem(string Name, decimal Price) : ICartAction;
sealed record RemoveItem(string Name) : ICartAction;
sealed record ApplyCoupon(string Code) : ICartAction;

// ---- Reducer: (state, action) -> new state. Pure, so it's trivial to test. ----
static class Cart
{
    public static CartState Reduce(CartState state, ICartAction action) => action switch
    {
        AddItem a => state with { Items = state.Items.Add((a.Name, a.Price)), Error = null },
        RemoveItem r => state with { Items = state.Items.RemoveAll(i => i.Name == r.Name), Error = null },
        ApplyCoupon { Code: "TENOFF" } => state with { DiscountPct = 10, Error = null },
        ApplyCoupon c => state with { Error = $"unknown coupon {c.Code}" },
        _ => state
    };
}

// ---- Store: the single source of truth ----
sealed class Store<TState, TAction>(TState initial, Func<TState, TAction, TState> reducer)
{
    private readonly List<Action<TState>> _subscribers = [];
    public List<TState> History { get; } = [initial];
    public TState State { get; private set; } = initial;

    public void Subscribe(Action<TState> onChange) => _subscribers.Add(onChange);

    public void Dispatch(TAction action)
    {
        State = reducer(State, action);
        History.Add(State);  // immutable snapshots make undo and time travel free
        foreach (var s in _subscribers) s(State);
    }
}
  render: 1 items, total 4.50
  render: 2 items, total 7.50
  render: 2 items, total 6.75 (-10%)
  render: 2 items, total 6.75 (-10%), error: unknown coupon BOGUS
  render: 1 items, total 4.05 (-10%)
history: 6 states, first total 0

The reducer is a single switch, and every way the cart can change is listed in it. The bad coupon doesn't throw. It becomes an error in state, which the view renders like anything else. And because each state is an immutable snapshot, the history list is free. That's how Redux DevTools does time travel.

A reducer must be pure, so where do network calls go? Into effects: code that runs after an action, does the I/O, and reports back by dispatching more actions. The Python version shows this with a feed that fails once and then loads:

import asyncio
from dataclasses import dataclass, replace


# ---- State ----
@dataclass(frozen=True)
class FeedState:
    loading: bool = False
    posts: tuple[str, ...] = ()
    error: str | None = None


# ---- Actions ----
@dataclass(frozen=True)
class RefreshTapped: ...
@dataclass(frozen=True)
class PostsLoaded:
    posts: tuple[str, ...]
@dataclass(frozen=True)
class LoadFailed:
    reason: str


# ---- Reducer: pure. No awaits, no I/O, no clock. ----
def reduce(state: FeedState, action) -> FeedState:
    match action:
        case RefreshTapped():
            return replace(state, loading=True, error=None)
        case PostsLoaded(posts):
            return replace(state, loading=False, posts=posts)
        case LoadFailed(reason):
            return replace(state, loading=False, error=reason)
    return state


# ---- Effects: the only place side effects live. They answer with more actions. ----
class FakeApi:
    def __init__(self):
        self.calls = 0

    async def fetch(self) -> tuple[str, ...]:
        self.calls += 1
        await asyncio.sleep(0.01)
        if self.calls == 1:
            raise ConnectionError("offline")
        return ("Hello", "Second post")


class Store:
    def __init__(self, state, api, render):
        self.state, self._api, self._render = state, api, render

    async def dispatch(self, action) -> None:
        self.state = reduce(self.state, action)
        self._render(self.state)
        if isinstance(action, RefreshTapped):  # this action has an effect
            try:
                await self.dispatch(PostsLoaded(await self._api.fetch()))
            except ConnectionError as e:
                await self.dispatch(LoadFailed(str(e)))


# The reducer test needs no store, no API and no event loop.
assert reduce(FeedState(), RefreshTapped()) == FeedState(loading=True)

store = Store(FeedState(), FakeApi(), render=lambda s: print("  render:", s))
asyncio.run(store.dispatch(RefreshTapped()))
asyncio.run(store.dispatch(RefreshTapped()))
  render: FeedState(loading=True, posts=(), error=None)
  render: FeedState(loading=False, posts=(), error='offline')
  render: FeedState(loading=True, posts=(), error=None)
  render: FeedState(loading=False, posts=('Hello', 'Second post'), error=None)

The reducer test on its own line is the selling point. It checks a state transition with no store, no fake API and no event loop. Everything that's hard to test (I/O, timing) is pushed out to the effect, and everything that's easy to get wrong (state transitions) is in a pure function.

On Android, the same reducer is a few lines of Kotlin. In a real app the state sits in a MutableStateFlow inside a ViewModel, and Compose collects it:

data class CounterState(val count: Int = 0, val error: String? = null)

sealed interface CounterAction {
    data object Increment : CounterAction
    data object Decrement : CounterAction
}

fun reduce(state: CounterState, action: CounterAction): CounterState = when (action) {
    CounterAction.Increment -> state.copy(count = state.count + 1, error = null)
    CounterAction.Decrement ->
        if (state.count == 0) state.copy(error = "can't go below zero")
        else state.copy(count = state.count - 1, error = null)
}

// In an Android ViewModel this is a MutableStateFlow; Compose collects it with collectAsStateWithLifecycle().
var state = CounterState()
listOf(CounterAction.Increment, CounterAction.Decrement, CounterAction.Decrement).forEach {
    state = reduce(state, it)
    println("render: $state")
}
render: CounterState(count=1, error=null)
render: CounterState(count=0, error=null)
render: CounterState(count=0, error=can't go below zero)

Notice that this isn't MVVM versus UDF. Android's recommended shape is a ViewModel that exposes a single immutable UiState and takes events through methods. That's MVVM for where the state lives, and unidirectional flow for how it changes.

The GoF pattern underneath. Each action is a Command that carries data but no behavior, so it can be logged, replayed or sent across a process boundary. Each immutable state is a Memento, which is why undo and time travel come almost free. I covered Memento in State, Iterator, Memento, Visitor and Interpreter. The store notifying the view is Observer again.

When not to use it. A full store with actions, a reducer and effects is a lot of ceremony for a settings screen with three toggles. It also gets awkward for fast-changing, local UI state, like a text field's cursor position or a drag gesture, which is better left inside the view. And one global store for a whole app can turn into a different kind of tangle, where unrelated features share one giant state tree. My rule of thumb: one store per screen or feature, and reach for it when the screen has state that several events can change.

Offline-first

The problem. The app treats the server as the source of truth and the network as always on. Open a screen in a lift or on a train, and you get a spinner, then an error, then an empty list. Worse, the user types a note, taps save, the request times out, and the note is gone.

The pattern. The local database is the source of truth for the UI. Reads always come from it, so the screen shows something immediately. Writes go to it first, together with an entry in a local outbox of pending changes, in one transaction. A sync engine pushes the outbox to the server when it can, and pulls changes made elsewhere. Android's offline-first guide calls this approach "lazy writes" and is clear about the hard part: conflicts.

Three details make sync safe:

  • Client-generated IDs, so a note has its identity before the server has ever seen it.
  • Idempotent pushes, so a retry after a lost response doesn't create a duplicate. Each outbox entry carries an operation ID the server remembers.
  • A conflict rule, decided up front, for when two devices edit the same thing.

The C# version covers the first two. The server's reply to the first push gets lost, so the client retries, and the server recognizes the operation:

var server = new FakeServer { Online = false };
var local = new LocalStore();
var repo = new NotesRepository(local);
var sync = new SyncEngine(local, server);

// 1. Offline: writes land locally and the UI shows them at once.
repo.Add("Buy film");
repo.Add("Charge batteries");
Console.WriteLine($"UI shows: {string.Join(", ", repo.All())} | pending: {local.Outbox.Count}");
sync.Run();

// 2. Back online, but the server's reply to the first push gets lost.
server.Online = true;
server.DropNextAck = true;
sync.Run();
sync.Run();  // retries: the server recognises the op id and doesn't apply it twice

// 3. Another device added a note; the next sync pulls it down.
server.Accept(new PendingOp("op-from-tablet", "n-tablet", "Book the ferry"));
sync.Run();
Console.WriteLine($"UI shows: {string.Join(", ", repo.All())} | server has {server.Notes.Count} notes");

record Note(string Id, string Text);
record PendingOp(string OpId, string NoteId, string Text);

// The local database is the source of truth for the UI. Notes and outbox change together.
sealed class LocalStore
{
    public Dictionary<string, Note> Notes { get; } = [];
    public List<PendingOp> Outbox { get; } = [];
    public int LastPulledVersion { get; set; }
}

sealed class NotesRepository(LocalStore db)
{
    private int _n;
    public void Add(string text)
    {
        var id = $"n{++_n}";                                // real apps: a client-generated UUID
        db.Notes[id] = new Note(id, text);                  // in SQLite, these two writes
        db.Outbox.Add(new PendingOp($"op{_n}", id, text));  // share one transaction
    }
    public IEnumerable<string> All() => db.Notes.Values.Select(n => n.Text);
}

sealed class SyncEngine(LocalStore db, FakeServer server)
{
    public void Run()
    {
        while (db.Outbox.Count > 0)                         // push, oldest first
        {
            var op = db.Outbox[0];
            try { server.Accept(op); }
            catch (IOException e) { Console.WriteLine($"  sync: push {op.OpId} failed ({e.Message}), will retry"); return; }
            db.Outbox.RemoveAt(0);
            Console.WriteLine($"  sync: pushed {op.OpId}");
        }
        var (changes, version) = server.ChangesSince(db.LastPulledVersion);  // then pull
        foreach (var n in changes) db.Notes[n.Id] = n;
        db.LastPulledVersion = version;
        Console.WriteLine($"  sync: pulled {changes.Count} change(s), now at v{version}");
    }
}

sealed class FakeServer
{
    public bool Online { get; set; } = true;
    public bool DropNextAck { get; set; }
    public Dictionary<string, (Note Note, int Version)> Notes { get; } = [];
    private readonly HashSet<string> _appliedOps = [];
    private int _version;

    public void Accept(PendingOp op)
    {
        if (!Online) throw new IOException("offline");
        if (_appliedOps.Add(op.OpId))                       // idempotent: apply each op once
            Notes[op.NoteId] = (new Note(op.NoteId, op.Text), ++_version);
        if (DropNextAck) { DropNextAck = false; throw new IOException("timeout, reply lost"); }
    }

    public (List<Note>, int) ChangesSince(int version) =>
        (Notes.Values.Where(n => n.Version > version).Select(n => n.Note).ToList(), _version);
}
UI shows: Buy film, Charge batteries | pending: 2
  sync: push op1 failed (offline), will retry
  sync: push op1 failed (timeout, reply lost), will retry
  sync: pushed op1
  sync: pushed op2
  sync: pulled 2 change(s), now at v2
  sync: pulled 1 change(s), now at v3
UI shows: Buy film, Charge batteries, Book the ferry | server has 3 notes

The note was saved on the server the first time, but the client never heard back. Without the operation ID, the retry would have created a second copy. That's the same idempotency key idea from the resilience post, with the phone as the client. The first pull brings back two changes because they're the device's own writes echoed back. A real sync protocol skips those, but applying them is harmless here because they match what's already stored.

The Python version uses SQLite (in the standard library) so the note and its outbox entry really do commit in one transaction, and it adds the third detail: a conflict between two devices, resolved with last-writer-wins:

import sqlite3
import uuid


class FakeServer:
    """Last-writer-wins per note, using the edit time the client sends."""

    def __init__(self):
        self.online = True
        self.notes: dict[str, tuple[str, int]] = {}  # id -> (text, edited_at)
        self.applied_ops: set[str] = set()

    def push(self, op_id, note_id, text, edited_at):
        if not self.online:
            raise ConnectionError("offline")
        if op_id in self.applied_ops:
            return  # a retry of something already applied
        self.applied_ops.add(op_id)
        current = self.notes.get(note_id)
        if current is None or edited_at > current[1]:
            self.notes[note_id] = (text, edited_at)

    def pull(self):
        return dict(self.notes)


class Phone:
    def __init__(self, server):
        self.server = server
        self.db = sqlite3.connect(":memory:")
        self.db.executescript("""
            CREATE TABLE notes  (id TEXT PRIMARY KEY, text TEXT, edited_at INTEGER);
            CREATE TABLE outbox (op_id TEXT PRIMARY KEY, note_id TEXT, text TEXT, edited_at INTEGER);
        """)

    def edit(self, note_id, text, edited_at):
        with self.db:  # one transaction: the note and its outbox entry commit together
            self.db.execute("INSERT OR REPLACE INTO notes VALUES (?, ?, ?)", (note_id, text, edited_at))
            self.db.execute("INSERT INTO outbox VALUES (?, ?, ?, ?)", (str(uuid.uuid4()), note_id, text, edited_at))

    def show(self, note_id):
        return self.db.execute("SELECT text FROM notes WHERE id = ?", (note_id,)).fetchone()[0]

    def sync(self):
        for op_id, note_id, text, edited_at in self.db.execute("SELECT * FROM outbox ORDER BY rowid").fetchall():
            try:
                self.server.push(op_id, note_id, text, edited_at)
            except ConnectionError:
                return "offline, kept outbox"
            with self.db:
                self.db.execute("DELETE FROM outbox WHERE op_id = ?", (op_id,))
        pending = {r[0] for r in self.db.execute("SELECT note_id FROM outbox")}
        with self.db:
            for note_id, (text, edited_at) in self.server.pull().items():
                if note_id not in pending:  # never clobber an edit that hasn't been pushed yet
                    self.db.execute("INSERT OR REPLACE INTO notes VALUES (?, ?, ?)", (note_id, text, edited_at))
        return "synced"


server = FakeServer()
phone, laptop = Phone(server), Phone(server)

phone.edit("trip", "Pack: camera", edited_at=1)
print("phone sync:", phone.sync())
laptop.sync()

server.online = False
phone.edit("trip", "Pack: camera, tripod", edited_at=5)       # offline edit on the phone
print("phone shows:", phone.show("trip"), "| phone sync:", phone.sync())

server.online = True
laptop.edit("trip", "Pack: camera, lenses", edited_at=3)      # older edit, synced first
print("laptop sync:", laptop.sync(), "| server:", server.notes["trip"][0])
print("phone sync:", phone.sync(), "| server:", server.notes["trip"][0])
laptop.sync()
print("laptop now shows:", laptop.show("trip"))
phone sync: synced
phone shows: Pack: camera, tripod | phone sync: offline, kept outbox
laptop sync: synced | server: Pack: camera, lenses
phone sync: synced | server: Pack: camera, tripod
laptop now shows: Pack: camera, tripod

The phone's offline edit was made later (time 5) than the laptop's (time 3), so it wins once the phone reconnects, even though the laptop synced first. The pull also refuses to overwrite a note that still has an unpushed local edit, which is what stops the phone's offline change from being clobbered before it's sent.

Now read the output again and notice what was lost: the laptop's "lenses". Last-writer-wins is simple and it's the common choice for mobile apps, but it throws away the losing edit. It also trusts the client's clock, which can be wrong. A server-assigned version number avoids the clock problem. If losing edits isn't acceptable, you need a smarter merge: per-field merging, keeping both versions and asking the user, or a CRDT, which is what the local-first community builds on.

The GoF pattern underneath. The repository the UI talks to is a Proxy: it stands in for the remote data and decides when to go to the network. Each outbox entry is a Command with an identity, queued and replayed later. The outbox itself is the transactional outbox from the messaging post, moved onto the device: save the data and the "message to send" together, and send afterwards.

When not to use it. Some writes must happen online, in real time. A bank transfer or a ticket purchase shouldn't sit in an outbox and succeed three hours later. Android's guide calls these online-only writes: try the network, and tell the user if it fails. Offline-first also costs a local schema, migrations on the device, a sync protocol and a conflict policy, so for an app that's mostly a thin view of live server data (a stock ticker, a live scoreboard), a simple HTTP cache gets you most of the benefit. Use offline-first for the user's own data, where losing their work is the worst outcome.

How they fit together

On a real screen, the three patterns stack:

View  --events-->  ViewModel / Store  --calls-->  Repository  --->  local DB + outbox
  ^                      |                            |                   ^
  |                      v                            v                   |
  +-------state------  reducer                   sync engine  <--->  server

The view sends events up. The view model or store turns them into new state, calling the repository for data. The repository reads and writes the local database and leaves the network to the sync engine. Each layer can be tested alone, and the screen keeps working when the network doesn't.

Next in the series, How Services Talk looks at the other end of that sync arrow: API gateways, backends for frontends, pub/sub and rate limiting.

Check yourself: questions and answers

1. Why shouldn't a view model reference UI types like a button or a list view?

Because the point of the view model is that it can be tested and reused without the UI. Once it holds a reference to a control, you need the UI framework to test it, and a redesign means rewriting it. The view model should expose state and commands, and let the view decide how to show them.

2. What makes a reducer "pure", and why does it matter?

Its output depends only on the state and the action passed in. It doesn't do I/O, read the clock or mutate its input. That makes every state transition a simple input-output test, and it makes features like undo, replay and time-travel debugging possible, because the same actions always produce the same states.

3. Where do side effects like network calls go in unidirectional data flow?

Outside the reducer, in effects (also called middleware, thunks or sagas, depending on the library). An effect reacts to an action, does the I/O, and dispatches new actions with the result. The reducer only ever sees plain data.

4. MVVM or unidirectional data flow: which should a new screen use?

Usually both. MVVM decides that state lives in a view model, not the view. Unidirectional flow decides how that state changes: as one immutable value, updated through events. Android's own guidance is a ViewModel exposing a single UI state stream, which is the two combined.

5. In an offline-first app, what is the source of truth, and why?

The local database. The UI reads only from it, so the screen always has something to show, and every change, whether from the user or from sync, goes through the same path. The server is where devices agree, but the UI never waits on it.

6. Why does every outbox entry need its own ID?

Because a push can succeed on the server while the response is lost. The client can't tell that apart from a failure, so it retries. With an operation ID, the server recognizes the retry and doesn't apply it twice. Without one, every flaky connection can create duplicates.

Further reading

  • Microsoft Learn, Model-View-ViewModel (from Enterprise Application Patterns Using .NET MAUI)
  • Microsoft Learn, Introduction to the MVVM Toolkit
  • Martin Fowler, Presentation Model
  • Apple Developer, Observation and Managing model data in your app
  • Android Developers, Guide to app architecture and UI layer (unidirectional data flow)
  • Android Developers, Build an offline-first app (lazy writes, sync and last-write-wins)
  • Redux, Three Principles
  • The Elm Guide, The Elm Architecture
  • Point-Free, The Composable Architecture
  • Ink & Switch, Local-first software
  • From this blog: SwiftUI Navigation and Architecture Patterns, Android Navigation and Architecture Patterns
← Previous

The Pattern Map: GoF to Cloud to AI

Next →

Two Azure Outages, and Why Known Problems Still Get Through

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.