-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoginViewModel.swift
More file actions
95 lines (81 loc) · 2.37 KB
/
LoginViewModel.swift
File metadata and controls
95 lines (81 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// LoginViewModel.swift
// DevLog
//
// Created by 최윤진 on 11/14/25.
//
import Foundation
@Observable
final class LoginViewModel: Store {
struct State: Equatable {
var isLoading = false
var showAlert: Bool = false
var alertTitle: String = ""
var alertMessage: String = ""
}
enum Action {
case setAlert(Bool)
case tapSignInButton(AuthProvider)
case setLoading(Bool)
}
enum SideEffect {
case signIn(AuthProvider)
}
private let signInUseCase: SignInUseCase
private let loadingState = LoadingState()
private(set) var state = State()
init(
signInUseCase: SignInUseCase
) {
self.signInUseCase = signInUseCase
}
func reduce(with action: Action) -> [SideEffect] {
var state = self.state
var effects: [SideEffect] = []
switch action {
case .setAlert(let isPresented):
setAlert(&state, isPresented: isPresented)
case .tapSignInButton(let authProvider):
effects = [.signIn(authProvider)]
case .setLoading(let value):
state.isLoading = value
}
if self.state != state { self.state = state }
return effects
}
func run(_ effect: SideEffect) {
switch effect {
case .signIn(let authProvider):
beginLoading(.immediate)
Task {
do {
defer { endLoading(.immediate) }
try await self.signInUseCase.execute(authProvider)
} catch {
if error.isSocialLoginCancelled { return }
send(.setAlert(true))
}
}
}
}
}
private extension LoginViewModel {
func setAlert(
_ state: inout State,
isPresented: Bool,
) {
state.alertTitle = String(localized: "common_error_title")
state.alertMessage = String(localized: "common_error_message")
state.showAlert = isPresented
}
func beginLoading(_ mode: LoadingState.Mode) {
loadingState.begin(mode: mode) { [weak self] isLoading in
self?.send(.setLoading(isLoading))
}
}
func endLoading(_ mode: LoadingState.Mode) {
loadingState.end(mode: mode) { [weak self] isLoading in
self?.send(.setLoading(isLoading))
}
}
}