Dependency Injection untuk ViewModels
Sisipkan layanan agar view model mudah diuji.
Dependency Injection untuk ViewModels adalah pelajaran SwiftUI Academy gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar SwiftUI Academy, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus SwiftUI Academy mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
The Hidden Dependency Problem
If a ViewModel creates its own network client inside itself, tests are stuck hitting the real server. That tight coupling makes it hard to swap later.
Inject Instead of Create
Dependency injection means passing in what a ViewModel needs from outside, rather than letting it build those services itself.
Define a Service Protocol
Describe the work with a protocol, not a concrete type. The ViewModel depends on the abstraction and never on a specific implementation.
protocol TaskService {
func fetch() async -> [Task]
}Accept It in the Initializer
Take the dependency through the init. Now any object that conforms to the protocol can be handed to the ViewModel.
init(service: TaskService) {
self.service = service
}Use the Injected Service
Inside methods, call the stored service rather than a hardcoded client. The ViewModel no longer cares who actually does the work.
tasks = await service.fetch()A Real Implementation
Your production type conforms to the protocol and talks to the network. You inject it when building the real screen.
struct LiveTaskService: TaskService {
func fetch() async -> [Task] { [] }
}A Mock for Tests
For tests, write a mock that returns fixed data instantly. Inject it to verify ViewModel logic without any real network calls.
struct MockTaskService: TaskService {
func fetch() async -> [Task] { sample }
}Tests Become Trivial
With a mock injected, a test just calls a method and checks the result. No waiting, no flakiness, only fast and predictable runs. ✅
A Default for Convenience
Give init a default real service so everyday code stays short, while tests can still override it with a mock when needed.
init(service: TaskService = LiveTaskService())Injecting via the Environment
For app-wide services, pass them through SwiftUI @Environment instead of every initializer, keeping call sites clean.
The Payoff
Injection makes ViewModels flexible and isolated. You can swap real, fake, or offline services without touching the view at all.
Quick Check
Why depend on a protocol instead of a concrete service?
Recap: Dependency Injection
You learned to inject services through a protocol, swap real for mock in tests, and even use @Environment for shared dependencies. That completes MVVM.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Dependency Injection untuk ViewModels” gratis?
Ya — teks lengkap “Dependency Injection untuk ViewModels” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus SwiftUI Academy, upgrade ke CoddyKit PRO. Kursus SwiftUI Academy mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Dependency Injection untuk ViewModels”?
Sisipkan layanan agar view model mudah diuji. Kamu berlatih SwiftUI Academy dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai SwiftUI Academy?
Tidak diperlukan pengalaman sebelumnya. SwiftUI Academy di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Dependency Injection untuk ViewModels” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran SwiftUI Academy ini?
Ya. Setiap pelajaran SwiftUI Academy menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Mengapa MVVM Cocok untuk SwiftUI
- Merancang ViewModel
- Menghubungkan Tampilan ke ViewModels
- Dependency Injection untuk ViewModels