Last active
October 7, 2022 16:58
-
-
Save codecat15/ef25f391bd3fedb6b37821252bba6b38 to your computer and use it in GitHub Desktop.
Dependency injection example of a service in MVVM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// factory to return the required protocol | |
class ServiceFactory { | |
func createLoginService() -> LoginService { | |
return LoginServiceImplementation() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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