Bird
Raised Fist0
Android Kotlinmobile~20 mins

Repository pattern in depth in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User List Screen
Displays a list of users fetched via a repository that abstracts data sources.
Target UI
-------------------------
| User List             |
|-----------------------|
| - Loading...          |
|                       |
|-----------------------|
| [Refresh Button]      |
-------------------------
Create a UserRepository interface with a method to get users.
Implement a UserRepositoryImpl that fetches users from a fake data source.
Create a ViewModel that uses the repository to get users.
Display the list of users in a RecyclerView.
Add a Refresh button to reload users from the repository.
Starter Code
Android Kotlin
package com.example.repositorypattern

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

// TODO: Define User data class

// TODO: Define UserRepository interface

// TODO: Implement UserRepositoryImpl with fake data

class UserViewModel(private val repository: UserRepository) : ViewModel() {
    private val _users = MutableStateFlow<List<User>>(emptyList())
    val users: StateFlow<List<User>> = _users

    fun loadUsers() {
        viewModelScope.launch {
            // TODO: Load users from repository and update _users
        }
    }
}

// TODO: Create UserListActivity with RecyclerView and Refresh button
// TODO: Connect ViewModel and update UI accordingly
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
Android Kotlin
package com.example.repositorypattern

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.widget.Button
import android.widget.TextView
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

// Data class representing a User
data class User(val id: Int, val name: String)

// Repository interface
interface UserRepository {
    suspend fun getUsers(): List<User>
}

// Implementation of UserRepository with fake data
class UserRepositoryImpl : UserRepository {
    override suspend fun getUsers(): List<User> {
        // Simulate network or database delay
        kotlinx.coroutines.delay(500)
        return listOf(
            User(1, "Alice"),
            User(2, "Bob"),
            User(3, "Charlie")
        )
    }
}

// ViewModel using the repository
class UserViewModel(private val repository: UserRepository) : ViewModel() {
    private val _users = MutableStateFlow<List<User>>(emptyList())
    val users: StateFlow<List<User>> = _users

    fun loadUsers() {
        viewModelScope.launch {
            val result = repository.getUsers()
            _users.value = result
        }
    }
}

// Factory to create UserViewModel with repository
class UserViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return UserViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

// Simple RecyclerView Adapter for User list
class UserAdapter(private var users: List<User>) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() {
    class UserViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)

    override fun onCreateViewHolder(parent: android.view.ViewGroup, viewType: Int): UserViewHolder {
        val textView = TextView(parent.context).apply {
            textSize = 20f
            setPadding(16, 16, 16, 16)
        }
        return UserViewHolder(textView)
    }

    override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        holder.textView.text = users[position].name
    }

    override fun getItemCount() = users.size

    fun updateUsers(newUsers: List<User>) {
        users = newUsers
        notifyDataSetChanged()
    }
}

// Activity displaying the user list
class UserListActivity : ComponentActivity() {
    private val repository = UserRepositoryImpl()
    private val viewModel: UserViewModel by viewModels { UserViewModelFactory(repository) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Root layout
        val rootLayout = android.widget.LinearLayout(this).apply {
            orientation = android.widget.LinearLayout.VERTICAL
            setPadding(16, 16, 16, 16)
        }

        // RecyclerView for users
        val recyclerView = RecyclerView(this).apply {
            layoutManager = LinearLayoutManager(this@UserListActivity)
        }

        val adapter = UserAdapter(emptyList())
        recyclerView.adapter = adapter

        // Refresh button
        val refreshButton = Button(this).apply {
            text = "Refresh"
            setOnClickListener {
                viewModel.loadUsers()
            }
        }

        rootLayout.addView(recyclerView, android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)
        rootLayout.addView(refreshButton, android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)

        setContentView(rootLayout)

        // Observe users from ViewModel
        viewModel.users
            .collectLatest { users ->
                adapter.updateUsers(users)
            }

        // Load users initially
        viewModel.loadUsers()
    }
}

This solution shows the repository pattern by defining a UserRepository interface that abstracts data fetching. The UserRepositoryImpl class simulates fetching users from a data source.

The UserViewModel uses this repository to load users asynchronously and exposes a StateFlow to the UI.

The UserListActivity sets up a simple UI with a RecyclerView to display users and a Refresh button to reload data. It observes the ViewModel's user list and updates the UI accordingly.

This pattern helps separate data logic from UI, making the app easier to maintain and test.

Final Result
Completed Screen
-------------------------
| User List             |
|-----------------------|
| Alice                 |
| Bob                   |
| Charlie               |
|                       |
|-----------------------|
| [Refresh Button]      |
-------------------------
When the screen opens, it shows the list of users: Alice, Bob, Charlie.
Tapping the Refresh button reloads the user list from the repository and updates the display.
Stretch Goal
Add a loading indicator that shows while users are being fetched.
💡 Hint
Use a MutableStateFlow<Boolean> in ViewModel to track loading state and show/hide a ProgressBar in the UI.

Practice

(1/5)
1. What is the main purpose of the Repository pattern in Android Kotlin development?
easy
A. To separate data access logic from UI components
B. To handle user interface animations
C. To manage app navigation between screens
D. To define the app's theme and styles

Solution

  1. Step 1: Understand the role of Repository

    The Repository pattern abstracts data sources and provides a clean API for data access.
  2. Step 2: Identify separation of concerns

    This pattern separates data handling from UI code, improving maintainability and testability.
  3. Final Answer:

    To separate data access logic from UI components -> Option A
  4. Quick Check:

    Repository pattern = separation of data and UI [OK]
Hint: Repository separates data logic from UI code [OK]
Common Mistakes:
  • Confusing Repository with UI or navigation components
  • Thinking Repository manages UI animations
  • Assuming Repository handles app styling
2. Which of the following is the correct way to declare a Repository interface in Kotlin?
easy
A. object UserRepository { val user = User() }
B. class UserRepository { fun getUser(id: Int): User }
C. fun UserRepository() { return User }
D. interface UserRepository { fun getUser(id: Int): User }

Solution

  1. Step 1: Identify interface syntax in Kotlin

    Interfaces use the interface keyword and declare functions without bodies.
  2. Step 2: Check each option

    interface UserRepository { fun getUser(id: Int): User } correctly declares an interface with a function signature. class UserRepository { fun getUser(id: Int): User } is a class, not interface. fun UserRepository() { return User } is invalid syntax. object UserRepository { val user = User() } is an object, not an interface.
  3. Final Answer:

    interface UserRepository { fun getUser(id: Int): User } -> Option D
  4. Quick Check:

    Kotlin interface syntax = interface UserRepository { fun getUser(id: Int): User } [OK]
Hint: Interfaces use 'interface' keyword with function signatures [OK]
Common Mistakes:
  • Using class instead of interface for Repository declaration
  • Writing invalid function syntax inside interface
  • Confusing object declaration with interface
3. Given this Kotlin code snippet, what will be printed?
class UserRepository {
  fun getUserName(id: Int): String {
    return if (id == 1) "Alice" else "Unknown"
  }
}

fun main() {
  val repo = UserRepository()
  println(repo.getUserName(1))
  println(repo.getUserName(2))
}
medium
A. 1\n2
B. Unknown\nAlice
C. Alice\nUnknown
D. Alice\nAlice

Solution

  1. Step 1: Analyze getUserName function

    If the id is 1, it returns "Alice", otherwise "Unknown".
  2. Step 2: Trace main function calls

    Calling getUserName(1) returns "Alice". Calling getUserName(2) returns "Unknown".
  3. Final Answer:

    Alice\nUnknown -> Option C
  4. Quick Check:

    id=1 returns Alice, else Unknown [OK]
Hint: Check if condition for id equals 1 [OK]
Common Mistakes:
  • Mixing up return values for different ids
  • Assuming numeric output instead of strings
  • Confusing order of print statements
4. Identify the error in this Kotlin Repository implementation:
class UserRepository {
  fun getUser(id: Int): User {
    return User()
  }
}

class User(val name: String)

fun main() {
  val repo = UserRepository()
  val user = repo.getUser(1)
  println(user.name)
}
medium
A. getUser function should return String, not User
B. User() requires a name parameter but none provided
C. UserRepository class must be an interface
D. println cannot print user.name

Solution

  1. Step 1: Check User class constructor

    User class requires a name parameter in its constructor.
  2. Step 2: Check UserRepository getUser return

    getUser returns User() without passing name, causing a compile error.
  3. Final Answer:

    User() requires a name parameter but none provided -> Option B
  4. Quick Check:

    Missing constructor argument causes error [OK]
Hint: Check constructor parameters when creating objects [OK]
Common Mistakes:
  • Ignoring required constructor parameters
  • Thinking class must be interface for Repository
  • Assuming println can't print properties
5. You want to create a Repository that fetches user data from both a local database and a remote API. Which approach best follows the Repository pattern principles?
hard
A. Create a Repository that combines local and remote data sources and exposes a unified API
B. Call the local database directly from UI and ignore remote API
C. Make UI components call remote API and local database separately
D. Use only remote API and discard local data storage

Solution

  1. Step 1: Understand Repository role with multiple data sources

    The Repository should abstract and combine data from local and remote sources.
  2. Step 2: Evaluate options for separation and abstraction

    Create a Repository that combines local and remote data sources and exposes a unified API correctly combines data sources and exposes a clean API. The other options break separation or ignore data sources.
  3. Final Answer:

    Create a Repository that combines local and remote data sources and exposes a unified API -> Option A
  4. Quick Check:

    Repository unifies data sources for UI [OK]
Hint: Repository unifies multiple data sources behind one API [OK]
Common Mistakes:
  • Accessing data sources directly from UI
  • Ignoring one data source completely
  • Mixing data calls in UI instead of Repository
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard