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:
@@ -2,14 +2,16 @@
|
||||
* 消息发送服务
|
||||
* 处理消息发送相关逻辑
|
||||
*
|
||||
* 重构说明:直接使用 zustand store 替代 IMessageStateManager
|
||||
* 重构说明:
|
||||
* - 直接使用 zustand store 替代 IMessageStateManager
|
||||
* - 移除了 SubscriptionManager 调用,Zustand 的 set() 会自动触发组件重渲染
|
||||
*/
|
||||
|
||||
import type { MessageResponse, MessageSegment, ConversationResponse } from '../../../types/dto';
|
||||
import { messageService } from '../../../services/messageService';
|
||||
import { saveMessage } from '../../../services/database';
|
||||
import type { IMessageSendService } from '../types';
|
||||
import { useMessageStore, subscriptionManager, mergeMessagesById } from '../store';
|
||||
import { useMessageStore, mergeMessagesById } from '../store';
|
||||
|
||||
export class MessageSendService implements IMessageSendService {
|
||||
private getCurrentUserId: () => string | null;
|
||||
@@ -53,28 +55,9 @@ export class MessageSendService implements IMessageSendService {
|
||||
const updatedMessages = mergeMessagesById(existingMessages, [newMessage]);
|
||||
store.setMessages(conversationId, updatedMessages);
|
||||
|
||||
// 关键:立即广播消息列表更新
|
||||
subscriptionManager.notifySubscribers({
|
||||
type: 'messages_updated',
|
||||
payload: {
|
||||
conversationId,
|
||||
messages: updatedMessages,
|
||||
newMessage,
|
||||
source: 'send',
|
||||
},
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 更新会话最后消息
|
||||
this.updateConversationWithNewMessage(conversationId, newMessage);
|
||||
|
||||
// 通知消息已发送
|
||||
subscriptionManager.notifySubscribers({
|
||||
type: 'message_sent',
|
||||
payload: { conversationId, message: newMessage },
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
|
||||
// 保存到本地数据库
|
||||
const textContent = segments
|
||||
?.filter((s: any) => s.type === 'text')
|
||||
@@ -100,11 +83,6 @@ export class MessageSendService implements IMessageSendService {
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('[MessageSendService] 发送消息失败:', error);
|
||||
subscriptionManager.notifySubscribers({
|
||||
type: 'error',
|
||||
payload: { error, context: 'sendMessage' },
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user