61 lines
1.7 KiB
Swift
61 lines
1.7 KiB
Swift
import CoreDomain
|
|
import CoreModel
|
|
import Observation
|
|
|
|
@MainActor
|
|
@Observable
|
|
public final class ProfileViewModel {
|
|
public private(set) var uiState: ProfileUiState = .loading
|
|
|
|
private let profileUseCase: ProfileUseCase
|
|
private let sessionUseCase: SessionUseCase
|
|
private var loadTask: Task<Void, Never>?
|
|
private var dataTask: Task<Void, Never>?
|
|
|
|
public init(profileUseCase: ProfileUseCase, sessionUseCase: SessionUseCase) {
|
|
self.profileUseCase = profileUseCase
|
|
self.sessionUseCase = sessionUseCase
|
|
}
|
|
|
|
public func load() {
|
|
loadTask?.cancel()
|
|
loadTask = Task { [weak self] in
|
|
guard let self else { return }
|
|
do {
|
|
for try await isLoggedIn in self.sessionUseCase.observeIsLoggedIn() {
|
|
self.handleLoginState(isLoggedIn)
|
|
}
|
|
} catch is CancellationError {
|
|
} catch {
|
|
self.uiState = .error(error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
|
|
public func logout() {
|
|
Task { [weak self] in
|
|
try? await self?.sessionUseCase.logout()
|
|
}
|
|
}
|
|
|
|
private func handleLoginState(_ isLoggedIn: Bool) {
|
|
dataTask?.cancel()
|
|
guard isLoggedIn else {
|
|
uiState = .loggedOut
|
|
return
|
|
}
|
|
uiState = .loading
|
|
dataTask = Task { [weak self] in
|
|
guard let self else { return }
|
|
do {
|
|
for try await profile in self.profileUseCase.observeProfile() {
|
|
self.uiState = .success(profile)
|
|
}
|
|
} catch is CancellationError {
|
|
} catch {
|
|
self.uiState = .error(error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
}
|