Skip to content

Instantly share code, notes, and snippets.

@codecat15
Last active October 7, 2022 16:58
Show Gist options
  • Save codecat15/ef25f391bd3fedb6b37821252bba6b38 to your computer and use it in GitHub Desktop.
Save codecat15/ef25f391bd3fedb6b37821252bba6b38 to your computer and use it in GitHub Desktop.
Dependency injection example of a service in MVVM
// LoginService Protocol
protocol LoginService: AnyObject {
func authenticateUser(request: LoginRequest) - > UserResponse
}
// Concrete implementation
class LoginServiceImplementation: LoginService {
func authenticateUser(request: LoginRequest) - > UserResponse {
// create the url request
// use the singleton here
HttpUtility.shared.get {
// handle response
}
}
}
protocol LoginViewModel: AnyObject {
func authenticateUser()
}
class LoginViewModelImplementation: LoginViewModel {
private let loginService: LoginService
// injecting the dependency
init(_service: LoginService) {
self.loginService = _service
}
func authenticateUser() {
// code
self.loginService.authenticateUser(request) {
// handle response
}
}
}
// factory to return the required protocol
class ServiceFactory {
func createLoginService() -> LoginService {
return LoginServiceImplementation()
}
}
class ViewModelFactory {
func createLoginViewModel -> LoginViewModel {
let service = ServiceFactory().createLoginService()
return LoginViewModelImplementation(_service: service)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment