Homework
Homework — why DI (swap a fake repo)
Homework — feel why DI is worth it.
- Move everything to Koin. Make sure
object Networkis deleted andMenuScreenuseskoinViewModel(). The menu should load as before. - Try
factoryvssingle. Temporarily changesingle { MenuRepository(get()) }tofactory { ... }and, via Logcat (or aprintlnin the constructor), watch how many times the repository is built.single— once;factory— on every request. - DI's payoff in tests (the important part). A test shouldn't need a real network. With DI you can hand it a fake repository:
class FakeMenuRepository : MenuRepository(FakeApi()) {
override suspend fun getMenu() = listOf(MenuItem(1, "Test pizza", "…", 8.5, "pizza", null))
}
// in the test:
startKoin { modules(module { viewModel { MenuViewModel(FakeMenuRepository()) } }) }
Without DI, MenuViewModel would build Network.api itself — and the test would always hit the network. With DI you swap the dependency in one line. That's the point of DI: not "prettier code," but the ability to substitute dependencies — in tests, in different builds, dev vs prod.
To submit: (1) the menu screen (via Koin), (2) the Logcat line [Koin] started with N definitions.
Next. The graph is ready and clean. In lesson 7 we add a Room cache — it's just one more
single { }in the modules, and the menu starts working even offline. DI now lets the app grow painlessly.