Files
ios-client/IosClientKit/Sources/FeatureHome/HomeViewModel.swift
2026-09-14 21:10:44 +08:00

35 lines
1023 B
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import CoreDomain
import CoreModel
import Observation
@MainActor
@Observable
public final class HomeViewModel {
public private(set) var uiState: HomeUiState = .loading
private let homeUseCase: HomeUseCase
private var loadTask: Task<Void, Never>?
public init(homeUseCase: HomeUseCase) {
self.homeUseCase = homeUseCase
}
public func load() {
// flatMapLatest 的等价:新 load 前先取消旧的观察。
loadTask?.cancel()
loadTask = Task { [weak self] in
guard let self else { return }
self.uiState = .loading
do {
for try await data in self.homeUseCase.observeHome() {
self.uiState = data.habits.isEmpty ? .empty : .success(data)
}
} catch is CancellationError {
// 被更新的 load() 取代,保持当前状态即可。
} catch {
self.uiState = .error(error.localizedDescription)
}
}
}
}