0Pricing
Android Academy · Lesson

Repository Pattern

Separate data access from UI with the Repository pattern. Coordinate between Room database and network API as single sources of truth.

Repository Pattern is a free Android Academy lesson on CoddyKit — lesson 4 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why a Repository?

As your app grows, the ViewModel can become cluttered with data-access code (Room queries, Retrofit calls, SharedPreferences reads).

The Repository pattern moves all data access behind a single class. The ViewModel only talks to the Repository — it doesn't care where the data comes from.

The Architecture Layers

The recommended Android architecture has three layers:

  • UI Layer — Activity/Fragment shows data, sends user events
  • ViewModel — holds state, processes events, calls Repository
  • Repository — fetches data from Room (local) or Retrofit (remote), decides which source to use

A Simple Repository

Create a Repository class that wraps your DAO and remote API:

class NoteRepository(private val dao: NoteDao) {

    // Expose a Flow that emits whenever data changes
    val allNotes = dao.getAllNotes()

    suspend fun insert(note: Note) {
        dao.insert(note)
    }

    suspend fun delete(note: Note) {
        dao.delete(note)
    }

    suspend fun update(note: Note) {
        dao.update(note)
    }
}

ViewModel Uses the Repository

The ViewModel gets data from the Repository — not directly from the DAO:

class NoteViewModel(private val repo: NoteRepository) : ViewModel() {

    val notes = repo.allNotes  // Flow from Repository

    fun addNote(title: String, body: String) {
        viewModelScope.launch {
            repo.insert(Note(title = title, body = body))
        }
    }

    fun deleteNote(note: Note) {
        viewModelScope.launch {
            repo.delete(note)
        }
    }
}

Cache-First Strategy

A common Repository pattern: cache-first. Show locally cached data immediately, then refresh from the network in the background:

  • 1. Emit cached data from Room immediately
  • 2. Fetch fresh data from API
  • 3. Save to Room — Flow updates automatically

This gives fast load times + eventually-fresh data.

Cache-First Implementation

Refresh the local DB from the network:

class ProductRepository(
    private val dao: ProductDao,
    private val api: ProductApiService
) {
    // Room Flow emits local data immediately
    val products = dao.getAllProducts()

    // Call this to sync with the server
    suspend fun refresh() {
        try {
            val remoteProducts = api.getProducts()
            dao.insertAll(remoteProducts)  // overwrites local cache
        } catch (e: Exception) {
            // Network failed — cached data is still shown
        }
    }
}

ViewModelFactory

When a ViewModel has constructor parameters, you need a ViewModelFactory to create it:

class NoteViewModelFactory(
    private val repo: NoteRepository
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        @Suppress("UNCHECKED_CAST")
        return NoteViewModel(repo) as T
    }
}

// In Activity:
val db = NoteDatabase.getInstance(this)
val repo = NoteRepository(db.noteDao())
val factory = NoteViewModelFactory(repo)
val viewModel = ViewModelProvider(this, factory)[NoteViewModel::class.java]

Hilt for Dependency Injection

Manually creating Repository and ViewModel instances gets tedious in large apps. Hilt (Dependency Injection) automates this:

  • Annotate your classes with @HiltViewModel, @Inject
  • Hilt creates and provides dependencies automatically
  • Removes all the factory boilerplate

Benefits Summary

The Repository pattern brings:

  • Testability — swap the real API with a fake for unit tests
  • Separation of concerns — ViewModel doesn't know if data is local or remote
  • Single source of truth — Room is always the source; API just refreshes it
  • Flexibility — add caching, pagination, or new data sources without touching the ViewModel

Quick Check

What is the main responsibility of the Repository in Android architecture?

Recap: Repository Pattern

You now understand the recommended Android architecture:

  • UI → ViewModel → Repository → (Room / Retrofit)
  • Repository is the single source of truth
  • Cache-first: show local data immediately, refresh in background
  • Use ViewModelFactory when ViewModel has constructor params
  • Hilt automates dependency injection in larger apps

Last course: Networking & Polish — Retrofit, images, and publishing.

Frequently asked questions

Is the “Repository Pattern” lesson free?

Yes — the full text of “Repository Pattern” is free to read here on the web, and the Android Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “Repository Pattern”?

Separate data access from UI with the Repository pattern. Coordinate between Room database and network API as single sources of truth. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 6, so you can start here or from the beginning and move at your own pace.

How long does the “Repository Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ViewModel & LiveData
  2. Room Database
  3. Coroutines & Suspend Functions
  4. Repository Pattern
  5. Navigation Component
  6. Dependency Injection with Hilt
← Back to Android Academy