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.

Lesson 4 of 611 steps

Repository Pattern is a free Android Academy lesson on CoddyKit. This is lesson 4 of 6. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 6 lessons in total.

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.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
36
Lessons
152

Frequently Asked Questions

Is the “Repository Pattern” lesson free?

Yes — any 3 lessons of the Android Academy learning path, including “Repository Pattern”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 6 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 6.

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