Skip to main content

MOBILE SERVICE

mobile-service.ts

Offline-first data with sync queue, conflict resolution, and retry.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to build mobile services that work offline-first with local reads, background sync queues, conflict resolution, and exponential backoff retry.

WHEN TO USE THIS

Any mobile feature that needs to work without a network connection.

AT A GLANCE

export class OfflineService {
  async read(id: string) {
    return localStore.get(id) ?? await api.fetch(id)
  }
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
import AsyncStorage from "@react-native-async-storage/async-storage";

export class OfflineService<T> {
  async read(id: string): Promise<T | null> {
    const local = await AsyncStorage.getItem(id);
    if (local) return JSON.parse(local);
    const remote = await this.api.fetch(id);
    if (remote) await AsyncStorage.setItem(id, JSON.stringify(remote));
    return remote;
  }

  async write(id: string, data: T): Promise<void> {
    await AsyncStorage.setItem(id, JSON.stringify(data));
    await this.syncQueue.enqueue({ id, data, timestamp: Date.now() });
  }
}
← All Patterns