Android Data Layer

new-silvermoon/awesome-android-agent-skills/.github/skills/architecture/android-data-layer

作者 new-silvermoon82900eacc8dbe13de93c6310af27b9df4b2bd2f6無授權條款收錄於 2026年10月9日更新於 2026年10月9日

Guidance on implementing the Data Layer using Repository pattern, Room (Local), and Retrofit (Remote) with offline-first synchronization.

AI 產生的概覽

指導 Android 開發者使用 Repository、Room、Retrofit 與 Hilt 建構離線優先的資料層。

功能
此技能提供指引,說明如何以 Repository 模式將 Android 應用程式的資料層組織為單一資料來源。內容涵蓋使用 Room 實體與回傳 Flow 的 DAO 進行本機持久化、使用 Retrofit 掛起函式進行遠端擷取,以及針對網路異常的錯誤處理。它也說明同步策略,例如讀取時的 stale-while-revalidate 與寫入時的 outbox 模式,以及透過 Hilt 模組將儲存庫介面綁定至實作。
適用情境
適用於規劃或實作需要快取、離線支援,或在本機資料庫與遠端 API 之間協調的 Android 應用程式資料層。也適合在決定如何組織儲存庫、Room DAO、Retrofit 服務與相依性注入綁定時使用。
執行需求
不包含指令碼或資源,僅為說明性內容。此指引假定專案使用 Kotlin、Room、Retrofit、Hilt 與 WorkManager,但閱讀它不需要安裝套件、認證資訊或網路存取。

Android Data Layer & Offline-First

Instructions

The Data Layer coordinates data from multiple sources.

1. Repository Pattern

  • Role: Single Source of Truth (SSOT).
  • Logic: The repository decides whether to return cached data or fetch fresh data.
  • Implementation:
    kotlin
    class NewsRepository @Inject constructor(    private val newsDao: NewsDao,    private val newsApi: NewsApi) {    // Expose data from Local DB as the source of truth    val newsStream: Flow<List<News>> = newsDao.getAllNews()
        // Sync operation    suspend fun refreshNews() {        val remoteNews = newsApi.fetchLatest()        newsDao.insertAll(remoteNews)    }}

2. Local Persistence (Room)

  • Usage: Primary cache and offline storage.
  • Entities: Define @Entity data classes.
  • DAOs: Return Flow<T> for observable data.

3. Remote Data (Retrofit)

  • Usage: Fetching data from backend.
  • Response: Use suspend functions in interfaces.
  • Error Handling: Wrap network calls in try-catch blocks or a Result wrapper to handle exceptions (NoInternet, 404, etc.) gracefully.

4. Synchronization

  • Read: "Stale-While-Revalidate". Show local data immediately, trigger a background refresh.
  • Write: "Outbox Pattern" (Advanced). Save local change immediately, mark as "unsynced", use WorkManager to push changes to server.

5. Dependency Injection

  • Bind Repository interfaces to implementations in a Hilt Module.
    kotlin
    @Bindsabstract fun bindNewsRepository(impl: OfflineFirstNewsRepository): NewsRepository

來源與署名

來源:new-silvermoon/awesome-android-agent-skills位於.github/skills/architecture/android-data-layer提交82900ea

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架