XuqmGroup-iOSSDK/XuqmDemo/Sources/ViewModels/ConversationViewModel.swift

77 行
2.5 KiB
Swift

import Foundation
import XuqmSDK
@MainActor
final class ConversationViewModel: ObservableObject {
@Published var conversations: [ConversationData] = []
@Published var state: ConversationLoadState = .idle
@Published var query: String = ""
@Published var totalUnreadCount: Int = 0
var filteredConversations: [ConversationData] {
if query.isEmpty { return conversations }
let keyword = query.trimmingCharacters(in: .whitespaces)
return conversations.filter {
$0.targetId.localizedCaseInsensitiveContains(keyword)
|| conversationPreview($0).localizedCaseInsensitiveContains(keyword)
}
}
func load() {
state = .loading
Task {
do {
conversations = try await ImSDK.shared.listConversations()
totalUnreadCount = conversations.reduce(0) { $0 + $1.unreadCount }
state = .loaded
} catch {
state = .error(error.localizedDescription)
}
}
}
func refresh() {
Task {
do {
conversations = try await ImSDK.shared.listConversations()
totalUnreadCount = conversations.reduce(0) { $0 + $1.unreadCount }
} catch {
state = .error(error.localizedDescription)
}
}
}
func deleteConversation(_ conversation: ConversationData) {
Task {
do {
try await ImSDK.shared.deleteConversation(targetId: conversation.targetId, chatType: conversation.chatType)
await refresh()
} catch {
state = .error(error.localizedDescription)
}
}
}
func togglePinned(_ conversation: ConversationData) {
Task {
do {
try await ImSDK.shared.setConversationPinned(targetId: conversation.targetId, chatType: conversation.chatType, pinned: !conversation.isPinned)
await refresh()
} catch {
state = .error(error.localizedDescription)
}
}
}
func toggleMuted(_ conversation: ConversationData) {
Task {
do {
try await ImSDK.shared.setConversationMuted(targetId: conversation.targetId, chatType: conversation.chatType, muted: !conversation.isMuted)
await refresh()
} catch {
state = .error(error.localizedDescription)
}
}
}
}