refactor(message): replace SubscriptionManager with Zustand selectors
Remove custom SubscriptionManager class and adopt Zustand's built-in selector mechanism for reactive state updates. This simplifies the architecture by eliminating manual subscription management and relying on Zustand's automatic dependency tracking for component re-renders. Key changes: - Remove SubscriptionManager class from store.ts - Replace all notifySubscribers calls with direct store updates - Update hooks to use Zustand selectors with useShallow for complex data - Remove subscribe/unsubscribe patterns from MessageManager - Simplify EmbeddedChat to use selector instead of local state - Rename requestConversationListRefresh to refreshConversations
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* 消息状态 Zustand Store
|
||||
* 使用 zustand 进行状态管理,提供响应式状态更新
|
||||
*
|
||||
*
|
||||
* 重构说明:
|
||||
* - 移除了 MessageStateManager 包装层
|
||||
* - 直接使用 zustand store 进行状态管理
|
||||
* - 订阅管理器集成到 store 中
|
||||
* - 移除了 SubscriptionManager,改用 Zustand selector 进行响应式订阅
|
||||
*/
|
||||
|
||||
import { create } from 'zustand';
|
||||
@@ -13,10 +13,6 @@ import type {
|
||||
ConversationResponse,
|
||||
MessageResponse,
|
||||
} from '../../types/dto';
|
||||
import type {
|
||||
MessageSubscriber,
|
||||
MessageEvent,
|
||||
} from './types';
|
||||
|
||||
// ==================== 状态接口 ====================
|
||||
|
||||
@@ -377,52 +373,3 @@ export const useMessageStore = create<MessageStore>((set, get) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// ==================== 订阅管理器 ====================
|
||||
|
||||
/**
|
||||
* 订阅管理器类
|
||||
* 管理消息事件的订阅和通知
|
||||
*/
|
||||
export class SubscriptionManager {
|
||||
private subscribers: Set<MessageSubscriber> = new Set();
|
||||
|
||||
subscribe(subscriber: MessageSubscriber): () => void {
|
||||
this.subscribers.add(subscriber);
|
||||
return () => {
|
||||
this.subscribers.delete(subscriber);
|
||||
};
|
||||
}
|
||||
|
||||
notifySubscribers(event: MessageEvent): void {
|
||||
this.subscribers.forEach(subscriber => {
|
||||
try {
|
||||
subscriber(event);
|
||||
} catch (error) {
|
||||
console.error('[SubscriptionManager] 订阅者执行失败:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.subscribers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// 创建全局订阅管理器实例
|
||||
export const subscriptionManager = new SubscriptionManager();
|
||||
|
||||
// ==================== 便捷方法 ====================
|
||||
|
||||
/**
|
||||
* 通知所有订阅者
|
||||
*/
|
||||
export function notifySubscribers(event: MessageEvent): void {
|
||||
subscriptionManager.notifySubscribers(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅消息事件
|
||||
*/
|
||||
export function subscribeToMessages(subscriber: MessageSubscriber): () => void {
|
||||
return subscriptionManager.subscribe(subscriber);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user