import { LogHelper } from '../log/LogHelper'; /** * ViewModel 基类 * * 提供统一的 ViewModel 功能,用于管理页面业务逻辑和状态 * * HarmonyOS 推荐使用方式: * - ViewModel 中使用普通属性管理状态 * - 页面中使用 @State viewModel,让 @State 自动响应 ViewModel 属性的变化 * - 不需要使用 StateFlow 或手动 observe */ /** * UI 状态基类 * * 定义通用的 UI 状态,所有 ViewModel 的状态类应继承此类 */ export class UiState { loading: boolean = false; error: string | null = null; constructor(loading: boolean = false, error: string | null = null) { this.loading = loading; this.error = error; } /** * 创建加载状态 */ static loading(): UiState { return new UiState(true, null); } /** * 创建错误状态 */ static error(message: string): UiState { return new UiState(false, message); } /** * 创建成功状态 */ static success(): UiState { return new UiState(false, null); } } /** * ViewModel 基类 * * 提供统一的 ViewModel 功能,与 Android 版本保持一致 * * 使用方式: * ```typescript * class LoginViewModel extends BaseViewModel { * @State loginState: LoginState = LoginState.Idle; * * async login(mobile: string, password: string) { * this.loginState = LoginState.Loading; * try { * const result = await authRepository.login(mobile, password); * if (result.isSuccess) { * this.loginState = LoginState.Success(result.getOrThrow()); * } else { * this.loginState = LoginState.Error(result.exceptionOrNull()?.message || '登录失败'); * } * } catch (error) { * this.loginState = LoginState.Error((error as Error).message); * } * } * } * ``` */ export abstract class BaseViewModel { protected readonly tag: string; constructor() { this.tag = this.constructor.name; } /** * ViewModel 初始化(可选) * * 在页面创建时调用 */ onInit(): void { // 子类可重写 } /** * ViewModel 销毁(可选) * * 在页面销毁时调用,用于清理资源 */ onDestroy(): void { // 子类可重写 } /** * 显示加载状态 */ protected setLoading(state: UiState, loading: boolean): void { if (state) { state.loading = loading; } } /** * 显示错误状态 */ protected setError(state: UiState, error: string): void { if (state) { state.error = error; state.loading = false; } } /** * 清除错误状态 */ protected clearError(state: UiState): void { if (state) { state.error = null; } } }